I am working on an exercise where a small piece of code based on a for-loop is converted to storing the same operation with a while loop. The conversion is incorrect for the purpose and looks like this:
int sum = 0; for (int i = 0; i < 4; i++) { if (i % 3 == 0) continue; sum += i; } System.out.println(sum);
This translates to:
int i = 0, sum = 0; while (i < 4) { if (i % 3 == 0) continue; sum += i; i++; } System.out.println(sum);
In the exercise, I will be asked to explain why the transformation is wrong, and then fix it. My thoughts:
With the initial value i = 0, this will immediately cause continue to continue after entering a wait loop, since (0% 3 == 0) will make if-statement true. As long as the initial value is 0, this will lead to a loop, so skip it an infinite number of times. I tried to change the initial value i = 1 , but noe sum is printed. Then I tried to increase i before the if-statement was executed, and now the program prints the sum 7. The question is: why the program will not be printed if I increased after the if statement, even if the initial value i = 1 tells (in my head) that the program should work right?
I made a table for each program to compare summation.
Version for the loop :
i = 0, sum + = I have not completed (continued), i ++
i = 1, sum = 1, i ++
i = 2, sum = 3, i ++
i = 3, sum + = I have not completed (continued), i ++
i = 4, i <4 false, stop stopped
Version of the while-loop:
i = 0, i ++, sum = 1
i = 1, i ++, sum = 3
i = 2, I ++, sum + = I have not completed (continued)
i = 3, i ++, sum = 7
i = 4, i <4 false, stop stopped
In the while-loop, the sum + = i is executed again than in for the loop . Is this the correct conversion method for a loop in a while-loop ?
int i = 0, sum = 0; while (i < 3) { i++; if (i % 3 == 0) continue; sum += i; } System.out.println(sum);