1. Member
Join Date
Feb 2009
Posts
2
Rep Power
0

## 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. 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. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
15
Since you know the limits of the summation, consider a for loop.

4. 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. Senior Member
Join Date
Sep 2008
Posts
564
Rep Power
9
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. Member
Join Date
Feb 2009
Posts
9
Rep Power
0
try this...:)

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

#### Posting Permissions

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