C++ for Loop and Range based for
A for loop repeats code a known number of times.
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
std::cout << "Round " << i << '\n';
}
}
Output
Round 1
Round 2
Round 3
Round 4
Round 5
Steps, counting down and sums
#include <iostream>
int main() {
for (int i = 0; i <= 20; i += 5) std::cout << i << ' ';
std::cout << '\n';
for (int i = 5; i >= 1; i--) std::cout << i << ' ';
std::cout << '\n';
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
std::cout << "Sum 1 to 100 = " << sum << '\n';
}
Output
0 5 10 15 20
5 4 3 2 1
Sum 1 to 100 = 5050
Nested loops
#include <iostream>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 5; j++) {
std::cout << i * j << '\t';
}
std::cout << '\n';
}
}
Output
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
Range based for loop
The easy way to go through a container or an array:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> fruits = {"apple", "banana", "mango"};
for (const std::string& fruit : fruits) { // const reference: no copy
std::cout << fruit << '\n';
}
std::vector<int> marks = {70, 85, 90};
for (int& m : marks) { // reference: we can change the items
m += 5;
}
for (auto m : marks) std::cout << m << ' ';
std::cout << '\n';
}
Output
apple
banana
mango
75 90 95
Range for with an initializer (C++20)
#include <iostream>
#include <vector>
int main() {
std::vector<char> letters = {'a', 'b', 'c'};
for (int index = 0; char c : letters) {
std::cout << index++ << ':' << c << ' ';
}
std::cout << '\n';
}
Output
0:a 1:b 2:c
Common mistakes
- Off by one:
i < 5runs 5 times (0 to 4),i <= 5runs 6 times. - Comparing a signed
intwithsize()(unsigned) gives a warning. Usestd::size_tor the range for. - Changing a container (adding items) while looping over it can break the loop.
Note:
Prefer the range based for. It is shorter and has no index mistakes. Next: C++ while and do while Loop.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |