Marie Mirbekian Marie Mirbekian - 3 months ago 9
Java Question

I think my code is correct but I keep getting zero?

Output that I want: 10 20 30 40 50..............
Output that I get: 0

public class HelloWorld
public static void main(String[] args)
final int n = 50;
int i= 0;
while(i <= n && i % 10 == 0 )

while(i <= n && i % 10 == 0 )

This is the continuation condition which is two expressions connected by logical-and &&.

That means both must be true for the whole thing to be true.

Now work out the two sub-expressions for when i becomes 1. The first will be true but not so the second (1 is not a multiple of 10), meaning the loop will exit at that point. That explains why you're only seeing 0.

To fix it, you need to separate the two sub-expressions since the loop control depends only on the first. However, you still only want printing to happen for multiples of ten (the second).

So, assuming as per your desired output 10 20 30 40 50, you don't want 0 as one of the outputs (despite it being, after all, a multiple of 10), the following pseudo-code will do the trick:

set n to 50, i to 1
while i is less than or equal to n:
    if the remainder when i is divided by 10 is 0:
        output i
    increment i

If you do want 0 included in the output, simply set i to 0 initially, and you'll see 0 10 20 30 40 50.

I've left the code above as pseudo-code on the assumption this is classwork of some description - it should be relatively easy to turn that into any procedural language.