In: Computer Science
What output is produced by the following code fragment?
int num = 0, max = 20;
while (num < max)
{
System.out.println(num);
num += 4;
}
Output:
0
4
8
12
16
Explanation:
Initially num = 0 and max = 20,
Iteration 1: num = 0, max = 20.
(num<max) ==> (0 < 20) which is true. So it goes inside while loop and prints the current max value i.e, 0. Then num+=4 means num = num +4 i.e, increments the num value by 4. So new num value = 0 + 4 = 4.
Iteration 2: num = 4, max = 20.
(num<max) ==> (4 < 20) which is true. So it goes inside while loop and prints the current max value i.e, 4. Then num+=4 means num = num +4 i.e, increments the num value by 4. So new num value = 4 + 4 = 8.
Iteration 3: num = 8, max = 20.
(num<max) ==> (8 < 20) which is true. So it goes inside while loop and prints the current max value i.e, 8. Then num+=4 means num = num +4 i.e, increments the num value by 4. So new num value = 8 + 4 = 12.
Iteration 4: num = 12, max = 20.
(num<max) ==> (12 < 20) which is true. So it goes inside while loop and prints the current max value i.e, 12. Then num+=4 means num = num +4 i.e, increments the num value by 4. So new num value = 12 + 4 = 16.
Iteration 5: num = 16, max = 20.
(num<max) ==> (16 < 20) which is true. So it goes inside while loop and prints the current max value i.e, 16. Then num+=4 means num = num +4 i.e, increments the num value by 4. So new num value = 16 + 4 = 20.
Iteration 6: num = 20, max = 20.
(num<max) ==> (20 < 20) which is false. So while loop terminates.