4.1 While Loop | 4.2 For Loop | 4.3 String Iteration | 4.4 Nested Iteration | Unit 4 Quiz |
Unit 4.4 - Nested Iteration
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);
}
}
Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
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--) { // PROBLEM: I changed it to say i >= 1 instead of i > 1 so that it includes the last row (i=1)
// 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();
Enter the number of rows:
Sample input: 5
Sample Output 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1