# While loop

• 02-23-2009, 10:58 PM
verbazon
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:

Code:

```counter = 0; num = kb.nextInt(); while (num < = counter) { counter++; }```
Thanks for the help in advance!
• 02-23-2009, 11:19 PM
sfe23
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);

}
}
• 02-24-2009, 01:09 AM
pbrockway2
Since you know the limits of the summation, consider a for loop.
• 02-24-2009, 01:20 AM
Fubarable
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.
• 02-24-2009, 02:07 AM
emceenugget
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
• 02-25-2009, 02:29 AM
kaemonsaionji
try this...:)

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