Results 1 to 6 of 6

Thread: While loop

  1. #1
    verbazon is offline Member
    Join Date
    Feb 2009
    Posts
    2
    Rep Power
    0

    Default While loop

    Hello all,

    I'm trying to write a loop that will compute the sum of the first n integers. For example, if n is 5, compute 1 + 2 + 3 + 4 + 5 = 15, and output the result.

    So far all I have is the following:

    Java Code:
    counter = 0;
    num = kb.nextInt();
    
    while (num < = counter) {
    counter++;
    }
    Thanks for the help in advance!

  2. #2
    sfe23's Avatar
    sfe23 is offline Member
    Join Date
    Feb 2009
    Posts
    42
    Rep Power
    0

    Default

    what is kb in your code?

    Anyway this isn't that hard.
    Try something like this:
    class Test{

    public static void main(String[] args)
    {
    int counter, n,sum;

    n=5; // since your example was 5
    counter =0;
    sum =0;
    while(counter <n){
    counter++;
    sum = sum + counter;

    }

    System.out.print("Sum of the first " + n + " integers is: " + sum);

    }
    }

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Since you know the limits of the summation, consider a for loop.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    We seem to be in a silly season where teachers are instructing their students to do for-type looping with any and all types of loops.

  5. #5
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    7

    Default

    i think it's just for the sake of learning the difference between loops. personally, i feel that it just pushes students to using only for-loops due to it being harder to mess up, all of the looping info all in the first line

  6. #6
    kaemonsaionji is offline Member
    Join Date
    Feb 2009
    Posts
    9
    Rep Power
    0

    Default

    try this...:)

    int j = 0;
    for(int i = 1; i <= n; i++)
    {
    j += i;
    }

Similar Threads

  1. for loop help
    By soc86 in forum New To Java
    Replies: 9
    Last Post: 01-24-2011, 10:45 PM
  2. For Loop
    By kian_hong2000 in forum New To Java
    Replies: 1
    Last Post: 08-07-2008, 03:01 PM
  3. while loop
    By Unknown1369 in forum New To Java
    Replies: 5
    Last Post: 07-08-2008, 11:15 AM
  4. How to use While loop
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-17-2008, 08:44 PM
  5. can you help me with this for loop?
    By java_fun2007 in forum New To Java
    Replies: 6
    Last Post: 12-22-2007, 11:20 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •