# for loop and while loop problems

• February 11th, 2010, 07:43 AM
Pulse_Irl
for loop and while loop problems
Write a program to do the following:
· Use a for loop to sum all of the numbers between 1 and 50 that are divisible by 5.
· Use a while loop to sum all of the numbers between 1 and 50 that are divisible by 5.
Check that you are getting the answer you expected!

Hi im getting a compile error for my for loop and ive no idea where to start with the while loop can anybody could point me in the right direction for my while loop

Code :

```class WS1Q2{ public static void main(String[] args){ int x, total= 0; for(x=1;x<=50;x++) { if(x / 5) { total = total + x; } } System.out.println("The total is "+total); }//close main }//close class```
• February 12th, 2010, 05:10 AM
Zhdophanti
Re: for loop and while loop problems
Try this (didn't compile it but i think it should work that way). And by the way, try to read the errors most time they will tell you whats wrong

"if (x / 5) {" -> x / 5 is no boolean expression, inside the brackets of an if-condition there must always be an expression which should be true or false

Code :

```class WS1Q2{ public static void main(String[] args){ int total= 0; for(int x=1;x<=50;x++) // as x is only need inside the loop initialize it there { if((x % 5) == 0) // % is modulo function, if x is dividable by 5 it will be zero { total = total + x; } } System.out.println("The total is "+total); }//close main }//close class```
• February 12th, 2010, 05:28 AM
Shambolic
Re: for loop and while loop problems
If you think about it, you can easily turn any for loop into a while loop.
Consider the following:
Code :

```for(initialise; condition; increment) { //stuff }```
How can you write that as a while loop? I'm sure you can figure it out!
• February 20th, 2010, 08:27 PM
mspray
Re: for loop and while loop problems
Here is a total solution incase you are still having difficulties

Code :

```public class Main {   /** * @param args the command line arguments */ public static void main(String[] args) { int total = 0; for(int i = 0; i <= 50; i++){ if(i%5 == 0){ total = total + i; } System.out.println("i is " + i + " Total is " + total); } total = 0; int x = 0; while(x <= 50){ if(x%5 == 0){ total = total + x; } x++; System.out.println("x is " + x + " total is " + total); }   }   }```
• May 3rd, 2010, 02:09 AM
lacome1102
Re: for loop and while loop problems
all your post are very good!