Summary - Loops
- C++ course
- Beginner
- Lesson 47/116
- 5 min
Combine for, while and range-based for to write a multiplication table.
Summary - Loops
In this group you learned five loop tools: for, while, do-while, range-based for and break/continue. Each is designed for a different need.
Now you have two combined tasks. First you will print twice the numbers from 1 to 3 with for, then sum the numbers from 1 to 5 with while. Such accumulation and loop tasks appear all the time in real programs.
Practice Print double (for)
Use a for (int i = 1; i <= 3; i++) loop to print twice the values 1, 2 and 3 with std::cout << (i * 2); on a single line. The output must be 246.
Starter code
#include <iostream>
int main() {
// Print twice 1 to 3
return 0;
}Sample solution
#include <iostream>
int main() {
for (int i = 1; i <= 3; i++) {
std::cout << (i * 2);
}
std::cout << std::endl;
return 0;
}Expected output
246
Practice Compute the sum (while)
The sum and i variables are set to 0 and 1. Inside a while (i <= 5) loop accumulate with sum += i; and increase i with i++. After the loop print sum with std::cout << sum;. The output must be 15.
Starter code
#include <iostream>
int main() {
int sum = 0;
int i = 1;
// Sum 1 to 5 with while
return 0;
}Sample solution
#include <iostream>
int main() {
int sum = 0;
int i = 1;
while (i <= 5) {
sum += i;
i++;
}
std::cout << sum << std::endl;
return 0;
}Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a for loop that runs 5 times?
// counted loop- for (int i = 0; i <= 5; i++)
- for (int i = 1; i < 5; i++)
- for (int i = 0; i < 4; i++)
- for (int i = 0; i < 5; i++) Correct answer
Explanation: i = 0, 1, 2, 3, 4 means 5 iterations.
2 Match each loop type to its scenario
| Term | Meaning |
|---|---|
for (int i = 0; i < n; i++) |
Counted loop |
while (cond) |
While condition holds |
do { } while (cond) |
At least once |
for (int x : v) |
Over a collection |
3 Write the range-based for symbol
std::vector<int> v = {1, 2, 3};
for (int x ____ v) { std::cout << x; }
std::vector<int> v = {1, 2, 3};
for (int x : v) { std::cout << x; }
Explanation: The : symbol is used in range-based for.