Control Flow
While Loop
A while loop repeats while its condition remains true.
while
A `while` loop checks the condition before each pass through the loop body.
While Loop
while_loop.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
int main() {
int start = 3;
int current = start;
int total = 0;
while (current > 0) {
total += current;
current--;
}
std::cout << "start=" << start << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
int main() {
int start = 1;
int current = start;
int total = 0;
while (current > 0) {
total += current;
current--;
}
std::cout << "start=" << start << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
#include <iostream>
int main() {
int start = 5;
int current = start;
int total = 0;
while (current > 0) {
total += current;
current--;
}
std::cout << "start=" << start << std::endl;
std::cout << "total=" << total << std::endl;
return 0;
}
start ← 3, current ← 3, total ← 0
3int main() {4 int start→ 3 = 3; //@start=1, 55 int current→ 3 = start3;6 int total→ 0 = 0;total ← 3, current ← 2
pass 1 of 38while (current3 > 0) {9 total→ 3 += current3;10 current→ 2--;11}All 3 passes — pass 1 is the card above pass totalcurrent1 0 → 3 3 → 2 2 3 → 5 2 → 1 3 5 → 6 1 → 0 std::cout << "start=" << start << std::endl;
13 std::cout << "start=" << start3 << std::endl;14 std::cout << "total=" << total6 << std::endl;15 return 0;16}outputstart=3 total=6
start ← 1, current ← 1, total ← 0
3int main() {4 int start→ 1 = 1;5 int current→ 1 = start1;6 int total→ 0 = 0;total ← 1, current ← 0
8while (current1 > 0) {9 total→ 1 += current1;10 current→ 0--;11}std::cout << "start=" << start << std::endl;
13 std::cout << "start=" << start1 << std::endl;14 std::cout << "total=" << total1 << std::endl;15 return 0;16}outputstart=1 total=1
start ← 5, current ← 5, total ← 0
3int main() {4 int start→ 5 = 5;5 int current→ 5 = start5;6 int total→ 0 = 0;total ← 5, current ← 4
pass 1 of 58while (current5 > 0) {9 total→ 5 += current5;10 current→ 4--;11}All 5 passes — pass 1 is the card above pass totalcurrent1 0 → 5 5 → 4 2 5 → 9 4 → 3 3 9 → 12 3 → 2 4 12 → 14 2 → 1 5 14 → 15 1 → 0 std::cout << "start=" << start << std::endl;
13 std::cout << "start=" << start5 << std::endl;14 std::cout << "total=" << total15 << std::endl;15 return 0;16}outputstart=5 total=15
Count Down to Zero
currentstarts at3.- The loop runs while
current > 0. - Each pass adds
currenttototal. - Each pass subtracts
1fromcurrent. - The final total is
6. | Current | Running total | | --- | --- | |3|3| |2|5| |1|6|
Exercise: while_loop.cpp
Use a while loop to count down from a start value and add the running total