![]() |
While Loops | For Loops | Nested Iteration | Code Example | Hacks | Quiz |
Unit 4.1 - While Loops
Unit 4 Team Teach
4.4 Nested Iteration
How to iterate through something to get a time complexity of O(n^2)
for (int i = 1; i <= 3; i++) { // Outer loop
System.out.println("Outer loop iteration: " + i);
for (int j = 1; j <= 3; j++) { // Inner loop
System.out.println(" Inner loop iteration: " + j);
}
}
What is wrong with this code cell(Hack)
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
for (int i = rows; i>1; i-) {
// Print numbers from 1 to i
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
// Move to next line after each row
System.out.println();
}
scanner.close();
Sample input: 5
Sample Output 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1