0
0
Javaprogramming~20 mins

Nested for loop in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nested Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested for loop with multiplication table
What is the output of the following Java code?
Java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 2; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.print(i * j + " ");
            }
            System.out.println();
        }
    }
}
A
1 2 3 
2 4 6 
B
1 2 3 
1 2 3 
C
1 1 1 
2 2 2 
D
1 3 6 
2 5 9 
Attempts:
2 left
💡 Hint
Think about how the outer and inner loops multiply their counters.
Predict Output
intermediate
1:30remaining
Number of iterations in nested loops
How many times will the innermost statement execute in this code?
Java
for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 5; j++) {
        System.out.println(i + "," + j);
    }
}
A10
B25
C20
D9
Attempts:
2 left
💡 Hint
Multiply the number of iterations of outer and inner loops.
🔧 Debug
advanced
2:00remaining
Identify the error in nested for loop
What error will this code produce when compiled?
Java
for (int i = 0; i < 3; i++)
    for (int j = 0; j < 2; j++)
        System.out.println(i + j);
}
ASyntaxError: missing semicolon
BSyntaxError: unexpected '}'
CNo error, runs fine
DRuntimeException: NullPointerException
Attempts:
2 left
💡 Hint
Check the braces and semicolons carefully.
Predict Output
advanced
2:00remaining
Output of nested loops with break statement
What is the output of this Java code?
Java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == 2) break;
                System.out.print(i * j + " ");
            }
            System.out.println();
        }
    }
}
A
1 
2 
3 
B
1 2 
2 4 
3 6 
C
1 2 3 
1 2 3 
1 2 3 
D
1 
2 
3 
4 
Attempts:
2 left
💡 Hint
The break stops the inner loop when j equals 2.
🧠 Conceptual
expert
2:30remaining
Effect of modifying loop variable inside nested loop
Consider this code snippet. What will be the value of i after the loops finish?
Java
int i = 0;
for (; i < 3; i++) {
    for (int j = 0; j < 2; j++) {
        if (j == 1) {
            i++;
        }
    }
}
System.out.println(i);
A5
B3
C6
D4
Attempts:
2 left
💡 Hint
Remember i is incremented both by the for loop and inside the inner loop.