Advertisements
Advertisements
Question
Rewrite the following program segment using a for loop.
int a = 5, b = 10;
while (b>0)
{b−=2;
}
System.out.println (a * b);
Code Writing
Long Answer
Advertisements
Solution
int a = 5, b;
for (b = 10; b > 0; b-=2)
{
// empty body
}
System.out.println(a * b);
b = 10is moved to the first part of theforloop.b > 0remains the same in the middle.- The expression
b-=2is moved to the last part of theforheader. Since the only action in thewhileloop was this update, the body of theforloop remains empty.
shaalaa.com
Is there an error in this question or solution?
