In: Computer Science
How many times will the following while loop iterate?
int i = 1;
while (i < 5)
{
i = i + 1;
System.out.println(“Hello!”);
}
Group of answer choices
4
0
5
It will iterate infinitely
Solution:
4 times.
Explanation:
The variable i is initialized with 1 initially.
Later, the while loop begins.
The condition for the loop is i<5.
The condition is checked and if the condition is evaluated as true, then the control enters the loop.
The value of i is incremented.
The message Hello is printed on console.
The loop continues its execution in this manner until the condition is false.
The execution of the above program is shown below and please refer the output for better understanding.
Screenshots:
The screenshot shows the execution of above code along with output which indicates the number of iterations of loop.