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, 0Notice 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, 0Skip 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, 0Use 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.
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