1(xvii)
Consider the program segment:
int p = 0; for(p = 4; p > 0; p -= 2); System.out.print(p); System.out.println(p);
The above statement will display:
- (a)42
- (b)4200
- (c)0
0 - (d)00
Show SolutionHide Solution↓
00
Reason
1. Initialization: int p = 0;
- This line declares an integer variable
pand initializes it to 0.
2. For Loop: for(p = 4; p > 0; p -= 2);
p = 4→ loop starts withpassigned the value 4.- Condition:
p > 0is true (since 4 > 0). - The semicolon (
;) at the end means the loop body is empty and does nothing. - Update:
p -= 2decreasespby 2. - Next value of
p= 2 → still > 0, so the loop continues. - Decrease again:
p -= 2→p = 0→ now the conditionp > 0is false, loop stops.
3. After the Loop: p is now 0.
4. Output Statements:
System.out.print(p);prints 0 without moving to the next line.System.out.println(p);prints 0 and moves to the next line.