Learn Java · lesson 19 of 61 · about 8 minutes
for Loops
Draw the group's seats row by row: count with for loops, and nest a loop for the seats inside a loop for the rows.
What you'll learn
- Write a counting for loop
- Count down and in steps
- Nest loops
A seat map
The desk says Rows needed: 1, but customers want to see their seats. Each row has 12 seats, so the desk should print a map like Row 1: XXXXXXX....., an X for each of the group's seats and a . for the rest. That's one loop for the rows with another loop for the 12 seats inside it.
Start; condition; step
for (int i = 0; i < 5; i++) sets i once, checks the condition before each lap, and runs the step after each lap.
Counting and a grid
public class Main {
public static void main(String[] args) {
for (int i = 10; i > 0; i -= 4) System.out.print(i + " ");
System.out.println();
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.printf("%4d", row * col);
}
System.out.println();
}
}
}Output
10 6 2
1 2 3
2 4 6
3 6 9Loops inside loops
A loop can sit inside another loop: for every lap of the outer loop, the inner one runs all the way through. Rows and columns are the classic use.
The seat map for 14 tickets
public class Main {
public static void main(String[] args) {
int tickets = 14;
int rowsNeeded = 2;
for (int r = 0; r < rowsNeeded; r++) {
String seats = "";
for (int s = 0; s < 12; s++) {
if (r * 12 + s < tickets) {
seats += "X";
} else {
seats += ".";
}
}
System.out.println("Row " + (r + 1) + ": " + seats);
}
}
}Output
Row 1: XXXXXXXXXXXX
Row 2: XX..........Tip
Seat s of row r is seat number r * 12 + s, counting from 0. Row 0 holds seats 0 to 11, row 1 holds 12 to 23, so the 14th ticket (number 13) lands in the second row.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.