C++ fundamentals · Lesson 5 of 21
Loops
for, while and do-while, break and continue, and nested loops.
10 minutes3 games
for when you know how many times. It has three parts: start, condition and step. while when repetition depends on a condition (like "until the number reaches zero").
C++
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
std::cout << i << " ";
}
std::cout << "\n";
int n = 4096, steps = 0;
while (n > 1) {
n /= 2;
steps++;
}
std::cout << "halved " << steps << " times\n";
return 0;
}Step by step1 / 8
- ▶int sum = 0;
- 2for (int i = 1; i <= 4; i++) {
- 3 sum += i;
- 4}
- 5std::cout << sum;
Variables
| sum | 0 |
Output
…
Follow i and sum on each pass.
break leaves the loop entirely; continue skips the rest of the current pass. do { } while (…) runs at least once before testing its condition.
C++
#include <iostream>
int main() {
// Nested loops: a small multiplication table
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= 4; c++) {
std::cout << r * c << "\t";
}
std::cout << "\n";
}
// First multiple of 7 above 50, skipping odd numbers
for (int x = 51; ; x++) {
if (x % 2 != 0) continue;
if (x % 7 == 0) {
std::cout << "found " << x << "\n";
break;
}
}
return 0;
}What's the output?
#include <iostream>
int main() {
int count = 0;
for (int i = 0; i < 10; i += 3) {
count++;
}
std::cout << count << "\n";
}What will this code print?
Order the lines
Order the code that prints the even numbers from 2 to 10.
- Click the lines in the right order
Exercise
Print the sum of the numbers from 1 to 100 that are divisible by 3 or 5.
Expected output: 2418
C++
#include <iostream>
int main() {
int sum = 0;
std::cout << sum << "\n";
return 0;
}Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.