Question:

Rewrite the following program segment using a for loop:

Given program segment:

int a = 5, b = 10; 
while (b > 0)
{
    b -= 2;
}
System.out.println(a * b);

Note: Ensure that the variable $b$ remains accessible for the System.out.println statement after the loop terminates.

Show Hint

To convert a \texttt{while} loop into a \texttt{for} loop, place the initialization, condition, and update parts inside the \texttt{for} statement in the same order.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Understand the working of the while loop.
The variable \( b \) is initially assigned the value \( 10 \). The loop continues as long as \( b>0 \). In each iteration, the value of \( b \) is decreased by \( 2 \).
Step 2: Identify the three parts needed in a for loop.
A \texttt{for} loop contains initialization, condition, and updation in one statement. Here:
Initialization: \( b = 10 \)
Condition: \( b>0 \)
Updation: \( b -= 2 \)
Step 3: Rewrite the loop in for loop form.
So, the equivalent \texttt{for} loop becomes:
\[ \begin{array}{l} \texttt{int a = 5, b = 10;} \\ \texttt{for (; b>0; b -= 2)} \\ \texttt{\{} \\ \texttt{\}} \\ \texttt{System.out.println(a * b);} \end{array} \]
Step 4: Write the final rewritten program.
Hence, the required program segment using a \texttt{for} loop is:
\[ \begin{array}{l} \texttt{int a = 5, b = 10;} \\ \texttt{for (; b>0; b -= 2)} \\ \texttt{\{} \\ \texttt{\}} \\ \texttt{System.out.println(a * b);} \end{array} \]
Was this answer helpful?
0
0

Questions Asked in ICSE Class X board exam

View More Questions