int count=0, sum=0;

while (count<5)

{

sum = sum + count;

System.out.println(sum);

count++;

}

thanks :)

Printable View

- 04-30-2010, 01:07 PMgt11990How can I rewrite the following while loop using a for loop?
int count=0, sum=0;

while (count<5)

{

sum = sum + count;

System.out.println(sum);

count++;

}

thanks :) - 04-30-2010, 01:17 PMj2me64
- 04-30-2010, 01:21 PMgt11990
can you explain (if possible) how you converted it into the for loop am really confused and new to this

thanks - 04-30-2010, 01:34 PMj2me64

easy, take the syntax of the for-loop

Code:`for (initialization; termination; increment) {`

statement(s)

}

and then replace the initialization, termination and increment according to your needs. your count was initialized with 0 so then initialization is 0, your while loop contain count < 5 so the termination is also i < 5 and the increment is 1 because your increment was count++ - 04-30-2010, 02:13 PMgt11990
Ohh i see thank you very much, this java is so complicated :)

- 04-30-2010, 05:05 PMgcalvin
That's close, and your explanation is correct, but I think this is a more accurate translation:

Code:`for (int count = 0, sum = 0; count < 5; count++) {`

sum += count;

System.out.println(sum);

}

Code:`int count, sum = 0;`

for (count = 0; count < 5; count++) {

sum += count;

System.out.println(sum);

}