|
||
|
|||
|
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 Java 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
|
|
|||
|
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 Java 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
|
|
|||
|
If you think about it, you can easily turn any for loop into a while loop.
Consider the following: Java Code
for(initialise; condition; increment)
{
//stuff
}
|
|
|||
|
Here is a total solution incase you are still having difficulties
Java 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);
}
}
}
|
|
|||
|
all your post are very good!
__________________
Raleigh Press Release Service |
![]() |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Need help with do-while loop | sk8rrr | Loops & Control Statements | 2 | 10-02-2010 11:33 PM |
| hi. i want to rewrite this do loop into a while loop. | etidd | Loops & Control Statements | 3 | 26-01-2010 09:27 PM |
| loop or what | silverspoon34 | Loops & Control Statements | 5 | 19-11-2009 06:10 PM |
| Need help with loop | SwEeTAcTioN | Loops & Control Statements | 8 | 25-10-2009 09:59 PM |
| [SOLVED] for loop | lotus | Loops & Control Statements | 2 | 13-07-2009 04:47 AM |