Give the output of the following program segment and also mention how many times the loop is executed:
int i;
for ( i = 5 ; i > 10; i ++ )
System.out.println( i );
System.out.println( i * 4 );
Answer:
Output of the above code is:
20
Loop executes 0 times.
Explanation
In the loop, i is initialized to 5 but the condition of the loop is i > 10. As 5 is less than 10 so the condition of the loop is false and it is not executed. There are no curly braces after the loop which means that the statement System.out.println( i ); is inside the loop and the statement System.out.println( i * 4 ); is outside the loop. Loop is not executed so System.out.println( i ); is not executed but System.out.println( i * 4 ); being outside the loop is executed and prints the output as 20 (i * 4 ⇒ 5 * 4 ⇒ 20).
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.