
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!

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);
}
}

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

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

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 forloops due to it being harder to mess up, all of the looping info all in the first line

try this...:)
int j = 0;
for(int i = 1; i <= n; i++)
{
j += i;
}