Welcome! Please Login or Sign Up.

Need help with coding in java, a while loop and for loop?

Discussion in 'Technology Forum' started by Giavex, Mar 20, 2012.


Thread Status:
Not open for further replies.
  1. Member

    Joined:
    Mar 21, 2008
    Posts:
    40
    Likes:
    61
    Trophy Points:
    6
    Here's the question:

    Write a program that asks the user to enter a positive, non-zero integer value. The program then sums up all the numbers between 0 and the integer entered. Use a while loop. Then use a for loop to write the same program.
    Once you have completed the above, extend the program with input validation. The program should repeatedly ask for an integer greater than 0, until the user enters valid input. Here is an example run:
    Please enter an integer greater than 0: -1
    Invalid input. Please enter an integer greater than 0: -10
    Invalid input. Please enter an integer greater than 0: 3
    The sum of the numbers between 0 and 3 is 6.

    Help please?? lol
     
    Giavex, Mar 20, 2012


    #1
  2. Classified

    Joined:
    May 23, 2007
    Posts:
    744
    Likes:
    16,060
    Trophy Points:
    421
    Re: Need help with coding in java, a while loop and for loop

    Code:
    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
    rookie is probably the only one on here that could help you with java.
     
  3. Member

    Joined:
    Oct 8, 2009
    Posts:
    87
    Likes:
    254
    Trophy Points:
    16
    Re: Need help with coding in java, a while loop and for loop

    If only I knew java. It was once being pushed for the classes I took, but it never happened.

    The best I could do is give you some pseudo code since I have programmed in some other languages.
     
  4. Member

    Joined:
    Sep 20, 2009
    Posts:
    61
    Likes:
    7
    Trophy Points:
    6
    Re: Need help with coding in java, a while loop and for loop

    Hope its not too late:

    User enters NUMBER

    int sum =0 ;
    for (int i=0; i<=NUMBER; i++)
    {
    sum= sum+(NUMBER-i);
    }

    Re: Need help with coding in java, a while loop and for loop

    the while loop looks like:

    User enters NUMBER

    while(NUMBER >= 0)
    {
    sum = sum + NUMBER;
    NUMBER--;
    }

    Re: Need help with coding in java, a while loop and for loop

    by no means where the above optimized for speed, just a quick code to get what you need to get done. The above should be the main part of the code producing the results. - Hope that helps.
     
    Last edited by a moderator: Oct 26, 2016
Thread Status:
Not open for further replies.

Share This Page