(x) Give the output of the following program segment and specify how many times the loop is executed.


String s = "JAVA";

for(i=0; i<s.length(); i+=2)
    System.out.println(s.substring(i));

Single Choice
Views 47

Answer:

Understanding the Code

The given Java program prints substrings of the string "JAVA" based on the loop conditions.


String s = "JAVA";
for(i=0; i<s.length(); i+=2)
    System.out.println(s.substring(i));

Step-by-Step Execution

  1. Initialization: i = 0

  2. Loop Condition: i < s.length(), i.e., i < 4 (since "JAVA" has 4 characters).

  3. Increment: i += 2 (i.e., i increases by 2 in each iteration).

  4. Printing: System.out.println(s.substring(i)) prints the substring starting from index i.

Iteration Breakdown

  • First Iteration (i = 0): s.substring(0)"JAVA"

  • Second Iteration (i = 2): s.substring(2)"VA"

  • Loop Stops (i = 4 is out of bounds)

Final Output


JAVA
VA

Number of Loop Executions

  • The loop runs 2 times (i = 0 and i = 2).

Final Answer

  • Output:


JAVA
VA

Number of times loop executes: 2

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of ICSE Computer Applications Class 10 – Previous Year Question Papers & Solutions, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.