- ATrue
- BFalse
- CDepends on the compiler
- DDepends on the standard
Time Taken:
Correct Answer:
Wrong Answer:
Percentage: %
Inheritance
nested loop
Certainly! Here is an example of a nested loop in Java:
public class NestedLoopExample { public static void main(String[] args) { // Outer loop for (int i = 1; i <= 3; i++) { System.out.println("Outer loop iteration: " + i); // Inner loop for (int j = 1; j <= 2; j++) { System.out.println(" Inner loop iteration: " + j); } } } }
Output:
Outer loop iteration: 1 Inner loop iteration: 1 Inner loop iteration: 2 Outer loop iteration: 2 Inner loop iteration: 1 Inner loop iteration: 2 Outer loop iteration: 3 Inner loop iteration: 1 Inner loop iteration: 2
In this example, the outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs 2 times. This demonstrates how nested loops work in Java.
both a and b
When the "break" statement is executed within the outer loop, then the outer loop will stop.
public class BreakOuterLoopExample { public static void main(String[] args) { // Outer loop for (int i = 1; i <= 3; i++) { System.out.println("Outer loop iteration: " + i); // Inner loop for (int j = 1; j <= 2; j++) { System.out.println(" Inner loop iteration: " + j); if (i == 2 && j == 1) { System.out.println(" Breaking out of the outer loop."); break; // Breaks out of the outer loop } } if (i == 2) { break; // Ensures the outer loop stops after the break in the inner loop } } } }
Output:
Outer loop iteration: 1 Inner loop iteration: 1 Inner loop iteration: 2 Outer loop iteration: 2 Inner loop iteration: 1 Breaking out of the outer loop.
In this example, the break statement inside the inner loop causes the outer loop to stop when i is 2 and j is 1. The outer loop does not continue after this point.
The break statement is used to exit the current loop.
Here is an example in Java to demonstrate its usage:
public class BreakStatementExample { public static void main(String[] args) { // Loop from 1 to 5 for (int i = 1; i <= 5; i++) { if (i == 3) { break; // Exit the loop when i is 3 } System.out.println("Iteration: " + i); } System.out.println("Loop exited."); } }
Output:
Iteration: 1 Iteration: 2 Loop exited.
In this example, the break statement exits the loop when i equals 3, so the loop stops executing and the program continues with the next statement after the loop.
Loop reduces the program code.
Using loops in programming helps to reduce redundancy by allowing a set of instructions to be executed repeatedly without having to write the same code multiple times. This makes the code more concise and easier to maintain.
If a 'for loop' is used within a 'for loop', it is called a nested for loop.
If a 'while loop' is used within a 'while loop', it is called a nested while loop.
If a 'do while loop' is used within a 'do while loop', it is called a nested do while loop.