This program fragment utilizes a while loop that starts with i initialized to 0. Inside the loop, i is incremented by 1 (i++) before printing its value with a space.
What happens in the code?
The loop continues until i reaches 5. Therefore, the output will be a sequence of numbers from 1 to 5 separated by spaces, resulting in the answer aligning with option A: "1 2 3 4 5".
The given program fragment uses a while loop to increment a variable from 1 to 5, printing each value with a space, resulting in the output "1 2 3 4 5".
The Complete Question
What is the output of the given program fragment?
A. 1 2 3 4 5
B. 0 1 2 3 4
C. 0 1 2 3 4 5
D. j j j j j
public class ProgramFragment {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
i++;
System.out.print(i + " ");
}
}
}