Faye Martin Faye Martin - 3 days ago 5
Java Question

Java Exercise in While Loop

I badly need help with this exercise.
I'm a newbie in Java and I hope someone could help me.
Here's the question:

Write a program called SumOfSeven to sum those
numbers from 1 to 100 that is divisible by 7. Display
the sum and the average. Use the “while-loop” to
answer this problem.

And here's my answer:

public class Practice {
public static void main(String[] args) {

int counter = 1;
int sum = 0;

while (counter<=100){
while (counter % 7 ==0){
sum+= counter;
}

counter++;
}
System.out.println("The sum is: " + sum);
}


}

I tried executing my answer but the software kept on loading and did not display any answer. I was able to successfully execute the program using this another code I made:

public class SumOfSeven {
public static void main(String[] args) {

int sum = 0;
int counter = 0;

while (counter<=100){
sum+= counter;
counter+=7;
}
System.out.println("The sum is: " + sum);
}


}

I just wanted to know why the first one didn't work.
Thanks in advance.

Best Regards,

Faye

Answer

Your inner while loop is infinite (when counter % 7 == 0, which is true in the 7th iteration of the outer while loop, when counter reaches 7) and pointless, since you only want to add counter to the sum one time when it is divisible by 7.

It should be replaced by an if statement :

while (counter<=100){
    if (counter % 7 ==0) {
        sum+= counter;
    }

    counter++;
}
Comments