All lessonsOpen Open Open Open Open
4. Loops
Introduction to loops
0 of 5 activities0%
Reading 1
while and for
A loop repeats a block.
while (condition) { ... } checks the condition, runs the body, and checks again.
for (init; condition; step) { ... } is convenient when you count. A common pattern is for (int i = 1; i <= n; i++).
i++ means add one to i.
int i = 1;
while (i <= 3) {
cout << i << endl;
i++;
}
for (int j = 1; j <= 3; j++) {
cout << j << endl;
}Check 2
for-loop pieces
In for (int i = 0; i < 5; i++), how many times does the body run?
Fill in 3
Loop keyword
Try it 4
Print 1 through 5
Run this for loop. Try changing 5 to 8.
main.cpp
Loading editor…
Output will appear here.
Assignment 5
Count to n
Read an integer n. Print the numbers 1 through n, each on its own line. You may assume n is at least 1.
main.cpp
Loading editor…