Variables and loops
C++ needs to know a variable's type. int holds whole numbers: int total = 0;
A for loop repeats code. for (int i = 1; i <= 5; i++) starts i at 1, keeps going while i <= 5, and adds 1 each time.
total += i; is short for total = total + i;. Open Step through to watch i and total change on every pass.
Example
for (int i = 1; i <= 3; i++) {
std::cout << "Round " << i << std::endl;
}
Output
Round 1 Round 2 Round 3
Changing the number in the loop condition changes how many times the loop runs.
Your tasks
0 of 3 done- Change the loop so it adds the numbers 1 to 10
- Store your favorite number in a new int variable
- Print that variable with std::cout
Tutor
The tutor guides you toward the answer instead of handing it over. It uses your own Claude usage.
Quick check
In the starter code, what is total after the loop?
No problems found. Unclosed tags, missing semicolons and errors show up here in plain words.
1#include <iostream>
2
3int main() {
4 int total = 0;
5 for (int i = 1; i <= 5; i++) {
6 total += i;
7 }
8 std::cout << "Total: " << total << std::endl;
9 return 0;
10}
total is created and set to 0.
Variables
| total | 0 |
Output
Step 1 of 14