Nested for loop in Java - Time & Space Complexity
When we use nested loops, the time it takes to run the code can grow quickly as the input gets bigger.
We want to understand how the running time changes when we add more items to process.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.println(i + "," + j);
}
}
This code prints pairs of numbers where both loops run from 0 to n-1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner loop's print statement runs repeatedly.
- How many times: The outer loop runs n times, and for each outer loop, the inner loop runs n times, so total n x n = n² times.
As n grows, the total number of print operations grows much faster because of the two loops inside each other.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 |
| 100 | 10,000 |
| 1000 | 1,000,000 |
Pattern observation: When n increases, the operations increase by the square of n, so doubling n makes operations about four times more.
Time Complexity: O(n²)
This means the running time grows very quickly as the input size grows because each item pairs with every other item.
[X] Wrong: "The nested loops only add up to O(n) because they just run one after another."
[OK] Correct: The loops are inside each other, so the inner loop runs completely for each outer loop step, multiplying the work, not just adding.
Understanding nested loops helps you explain how your code handles bigger inputs and shows you can think about efficiency clearly.
"What if the inner loop ran only up to a fixed number instead of n? How would the time complexity change?"
Practice
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
// code
}
}Solution
Step 1: Analyze nested loop iterations
The outer loop runs 3 times, and for each outer loop iteration, the inner loop runs 2 times.Step 2: Explain the repetition behavior
This means the inner loop runs fully inside each outer loop iteration, repeating code multiple times in total.Final Answer:
Runs one loop inside another to repeat code multiple times -> Option AQuick Check:
Nested loops = inner loop inside outer loop [OK]
- Thinking loops run sequentially, not nested
- Confusing inner and outer loop counts
- Assuming only one loop runs multiple times
Solution
Step 1: Verify Java for loop syntax requirements
Java for loops require parentheses around initialization, condition, and increment, and braces for blocks.Step 2: Identify correct nested loop syntax
for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) System.out.println(i + j); } correctly uses braces for outer loop without extra invalid keywords or else blocks.Final Answer:
for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) System.out.println(i + j); } -> Option AQuick Check:
Correct Java syntax = for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) System.out.println(i + j); } [OK]
- Missing parentheses around for loop conditions
- Using else after for loop incorrectly
- Omitting braces for multiple statements
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}Solution
Step 1: Trace outer loop iterations
Outer loop runs i=1 and i=2.Step 2: Calculate inner loop outputs for each i
For i=1: j=1,2,3 outputs 1*1=1, 1*2=2, 1*3=3.
For i=2: j=1,2,3 outputs 2*1=2, 2*2=4, 2*3=6.Final Answer:
1 2 3 2 4 6 -> Option DQuick Check:
Multiply i and j in nested loops = 1 2 3 2 4 6 [OK]
- Ignoring new line after inner loop
- Concatenating all numbers in one line
- Mixing up i and j values
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.println(i + j);
}
}Solution
Step 1: Check braces matching
The inner loop lacks braces but has an extra closing brace '}' after it, causing syntax error.Step 2: Identify correct brace placement
Remove the extra '}' after inner loop or add braces properly to fix syntax.Final Answer:
Extra closing brace '}' after inner loop -> Option CQuick Check:
Brace mismatch error = Extra closing brace '}' after inner loop [OK]
- Adding extra braces after loops
- Omitting braces for multiple statements
- Incorrect loop conditions
Solution
Step 1: Set outer loop for rows 1 to 4
The outer loop controls the row number from 1 to 4.Step 2: Set inner loop for columns 1 to 4 and print product
The inner loop runs columns 1 to 4, printing the product of row and column numbers to form the table.Final Answer:
Use outer loop for rows 1 to 4 and inner loop for columns 1 to 4, print product -> Option BQuick Check:
Nested loops for rows and columns = Use outer loop for rows 1 to 4 and inner loop for columns 1 to 4, print product [OK]
- Using single loop for 2D table
- Not printing product of both loop variables
- Skipping inner loop printing
Ready to prove it?
Pass the test and this pattern moves unknown
