Control Flow
For Loop
A for loop is useful when code needs an index variable.
For Loop
for_loop.cpp
#include <iostream>
int main() {
int values[4] = {3, 5, 7, 9};
int multiplier = ;
int total = 0;
for (int i = 0; i < 4; i++) {
total += values[i] * multiplier;
}
std::cout << "multiplier=" << multiplier << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
int main() {
int values[4] = {3, 5, 7, 9};
int multiplier = ;
int total = 0;
for (int i = 0; i < 4; i++) {
total += values[i] * multiplier;
}
std::cout << "multiplier=" << multiplier << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
int main() {
int values[4] = {3, 5, 7, 9};
int multiplier = ;
int total = 0;
for (int i = 0; i < 4; i++) {
total += values[i] * multiplier;
}
std::cout << "multiplier=" << multiplier << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
indexed loop
An indexed loop can use `i` to read each array element by position.