What is the value of k after the following code fragment? int k = 0; int n = 12 while (k < n) { k = k + 1; }
-
O
-
11
-
12
-
-3
To solve this question, the user needs to understand the basic control flow of the while loop and the concept of variable assignment.
The code initializes the variable k to 0 and the variable n to 12. The while loop continues running as long as the value of k is less than the value of n. In each iteration of the loop, the value of k is incremented by 1.
Since the loop runs 12 times, the value of k will be incremented 12 times. Therefore, at the end of the loop, the value of k will be equal to 12.
Now, let's go through each option and explain why it is right or wrong:
A. O: This option is incorrect because the value of k is incremented 12 times, resulting in a final value of 12, not 0.
B. 11: This option is incorrect because the value of k is incremented 12 times, resulting in a final value of 12, not 11.
C. 12: This option is correct. The value of k is incremented 12 times, resulting in a final value of 12.
D. -3: This option is incorrect because the loop increments the value of k by 1 each time, and the starting value of k is 0. Therefore, the value of k can never be negative.
The Answer is: C
Trace the loop: k starts at 0, n = 12. The while condition (k < n) is checked before each iteration, and the body simply increments k by 1. So k goes 0→1→2→...→12. Once k reaches 12, the condition (12 < 12) is false, so the loop exits with k = 12. Option '0' would only be correct if the loop never ran, which it does. '11' would be the value the last time the condition was still true (right before the final increment), not after the loop ends. '-3' has no relationship to the code at all - there's no decrement or negative arithmetic anywhere in the fragment. The loop is a simple bounded counter, and it always terminates with k equal to n, i.e., 12.