Question:

Give the output of the following program segment and mention how many times the loop is executed.

int K = 1;
do
{
   K += 2;
    System.out.println(K);
} while (K <= 6);

Show Hint

A \texttt{do-while} loop always executes at least once because the condition is checked after the loop body runs.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Write the initial value of \(K\).
Initially,
\[ K = 1 \] Step 2: Understand the working of the \texttt{do-while} loop.
In a \texttt{do-while} loop, the statements inside the loop are executed first, and only after that the condition is checked. So the loop will run at least one time.
Step 3: Execute the loop step by step.
First iteration:
\[ K = 1 + 2 = 3 \] So, \(3\) is printed. Since \(3 \leq 6\), the loop continues.
Second iteration:
\[ K = 3 + 2 = 5 \] So, \(5\) is printed. Since \(5 \leq 6\), the loop continues.
Third iteration:
\[ K = 5 + 2 = 7 \] So, \(7\) is printed. Now \(7 \leq 6\) is false, so the loop stops.
Step 4: Write the output.
Hence, the output is:
\texttt{3}
\texttt{5}
\texttt{7}
Step 5: Count the number of loop executions.
The loop is executed \(3\) times.
Was this answer helpful?
0
0

Top Questions on Control Statements

View More Questions

Questions Asked in ICSE Class X board exam

View More Questions