0
0
Javaprogramming~20 mins

Loop execution flow in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested loops with break
What is the output of the following Java code snippet?
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 + " ");
            }
        }
    }
}
A1-1 1-2 1-3 2-1 2-2 2-3 3-1 3-2 3-3
B1-1 1-2 2-1 2-2 3-1 3-2
C1-1 2-1 3-1 3-2
D1-1 2-1 3-1
Attempts:
2 left
💡 Hint
Remember that break exits the innermost loop immediately.
Predict Output
intermediate
2:00remaining
Output of while loop with continue
What will be printed by this Java code?
Java
public class Main {
    public static void main(String[] args) {
        int i = 0;
        while (i < 5) {
            i++;
            if (i == 3) {
                continue;
            }
            System.out.print(i + " ");
        }
    }
}
A2 3 4 5
B1 2 3 4 5
C1 2 4 5
D1 2 3 4
Attempts:
2 left
💡 Hint
The continue skips the print when i equals 3.
🔧 Debug
advanced
2:00remaining
Identify the error in for loop increment
What error will this Java code produce when run?
Java
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i = i++) {
            System.out.print(i + " ");
        }
    }
}
AInfinite loop printing 0 repeatedly
BCompilation error: invalid increment expression
CPrints 0 1 2 3 4
DRuntime exception: ArrayIndexOutOfBoundsException
Attempts:
2 left
💡 Hint
Look carefully at the increment expression i = i++.
Predict Output
advanced
2:00remaining
Output of for loop with multiple variables
What is the output of this Java code?
Java
public class Main {
    public static void main(String[] args) {
        for (int i = 0, j = 5; i < j; i++, j--) {
            System.out.print(i + "-" + j + " ");
        }
    }
}
A0-5 1-4 2-3 3-2
B0-5 1-4 2-3
C0-5 1-4 2-3 3-2 4-1
D0-5 1-4
Attempts:
2 left
💡 Hint
The loop stops when i is no longer less than j.
🧠 Conceptual
expert
2:00remaining
Number of iterations in nested loops with dependent conditions
Consider the following Java code. How many times will the innermost print statement execute?
Java
public class Main {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 1; i <= 4; i++) {
            for (int j = i; j <= 4; j++) {
                count++;
            }
        }
        System.out.println(count);
    }
}
A10
B16
C20
D8
Attempts:
2 left
💡 Hint
Count how many times j runs for each i.