Menu
Coddy logo textTech

For Loop Part 2

Part of the Fundamentals section of Coddy's Java journey — lesson 47 of 73.

let's explore some cool variations of the for loop condition:

Counting Backwards:

for (int i = 10; i >= 0; i--) {
    System.out.println(i);
}
// Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0

Notice how we start with a higher number (i = 10), Use i >= 0 as our condition and use i-- to decrease the counter

Want to skip numbers? Just change the increment/decrement value:

// Counting up by 2s
for (int i = 0; i <= 10; i += 2) {
    System.out.println(i);
}
// Output: 0, 2, 4, 6, 8, 10
// Counting down by 2s
for (int i = 10; i >= 0; i -= 2) {
    System.out.println(i);
}
// Output: 10, 8, 6, 4, 2, 0 

You can even use multiple variables in your loop control:

for (int i = 0, j = 10; i <= 10; i++, j--) {
    System.out.println("i = " + i + ", j = " + j);
}
// Output: i = 0, j = 10
//         i = 1, j = 9
//         i = 2, j = 8
// And so on...

Cheat sheet

For loops can count backwards by starting with a higher number and using decrement:

for (int i = 10; i >= 0; i--) {
    System.out.println(i);
}
// Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0

Skip numbers by changing the increment/decrement value:

// Counting up by 2s
for (int i = 0; i <= 10; i += 2) {
    System.out.println(i);
}
// Output: 0, 2, 4, 6, 8, 10

// Counting down by 2s
for (int i = 10; i >= 0; i -= 2) {
    System.out.println(i);
}
// Output: 10, 8, 6, 4, 2, 0

Use multiple variables in loop control:

for (int i = 0, j = 10; i <= 10; i++, j--) {
    System.out.println("i = " + i + ", j = " + j);
}

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals