Nested Loop
Part of the Fundamentals section of Coddy's Java journey — lesson 48 of 73.
A nested loop is simply a loop inside another loop. The inner loop will complete all its iterations for each single iteration of the outer loop.
A good analogy for this is a clock: for each hour (outer loop), the minute hand (inner loop) must complete its full 60-minute cycle.
Example of a nested loop:
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
System.out.println(x + " " + y);
}
}
// This will output:
// 0 0
// 0 1
// 1 0
// 1 1The outer loop (x) runs twice, and for each of those times, the inner loop (y) runs twice.
Challenge
BeginnerWrite a program that prints a rectangle of asterisks (*) with a given width and height.
Input: Two integers: width and height
For example:
If width = 5 and height = 3, the output should be:
*****
*****
*****If width = 4 and height = 6, the output should be:
****
****
****
****
****
****Cheat sheet
A nested loop is a loop inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.
Basic nested loop structure:
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
System.out.println(x + " " + y);
}
}
// Output:
// 0 0
// 0 1
// 1 0
// 1 1The outer loop runs completely, and for each iteration of the outer loop, the inner loop runs all of its iterations.
Try it yourself
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int width = scanner.nextInt();
int height = scanner.nextInt();
// Write your code below
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else