For Loop Part 2
Part of the Fundamentals section of Coddy's C++ journey — lesson 47 of 74.
Let's explore some cool variations of the for loop condition
Counting Backwards:
for (int i = 10; i >= 0; i--) {
std::cout << 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) {
std::cout << i << " ";
}
// Output: 0 2 4 6 8 10// Counting down by 2s
for (int i = 10; i >= 0; i-=2) {
std::cout << i << " ";
}
// Output: 10 8 6 4 2 0You can even use multiple variables in your loop control:
for (int i = 0, j = 10; i <= 10; i++, j--) {
std::cout << "i = " << i << " " << "j = " << j << " ";
}
// Output: i = 0 j = 10
// i = 1 j = 9
// i = 2 j = 8
// And so on...In this example, we have two counter variables, i and j, initialized to 0 and 10, respectively. In each iteration, i is incremented by 1 and j is decremented by 1. The loop continues as long as i is less than or equal to 10.
Cheat sheet
For loops can count backwards by starting with a higher number, using >= as condition, and decrementing:
for (int i = 10; i >= 0; i--) {
std::cout << 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) {
std::cout << i << " ";
}
// Output: 0 2 4 6 8 10
// Counting down by 2s
for (int i = 10; i >= 0; i-=2) {
std::cout << i << " ";
}
// Output: 10 8 6 4 2 0Use multiple variables in loop control:
for (int i = 0, j = 10; i <= 10; i++, j--) {
std::cout << "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 Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else