Foundations
Loops
A for loop repeats work while a counter changes.
for
`for (init; condition; step)` groups the loop setup, test, and update.
accumulator
An accumulator variable carries a running value across loop iterations.
Loops
loops.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int limit = 4;
int total = 0;
for (int i = 1; i <= limit; i++) {
total += i;
}
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int limit = 3;
int total = 0;
for (int i = 1; i <= limit; i++) {
total += i;
}
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int limit = 5;
int total = 0;
for (int i = 1; i <= limit; i++) {
total += i;
}
printf("total=%d\n", total);
return 0;
}
limit ← 4, total ← 0
3int main(void) {4 int limit→ 4 = 4; //@limit=3, 55 int total→ 0 = 0;total ← 1
pass 1 of 47for (int i1 = 1; i <= limit4; i++) {8 total→ 1 += i1;9}All 4 passes — pass 1 is the card above pass itotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 printf("total=%d ", total);
11 printf("total=%d\n", total10);12 return 0;13}outputtotal=10
limit ← 3, total ← 0
3int main(void) {4 int limit→ 3 = 3;5 int total→ 0 = 0;total ← 1
pass 1 of 37for (int i1 = 1; i <= limit3; i++) {8 total→ 1 += i1;9}All 3 passes — pass 1 is the card above pass itotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 printf("total=%d ", total);
11 printf("total=%d\n", total6);12 return 0;13}outputtotal=6
limit ← 5, total ← 0
3int main(void) {4 int limit→ 5 = 5;5 int total→ 0 = 0;total ← 1
pass 1 of 57for (int i1 = 1; i <= limit5; i++) {8 total→ 1 += i1;9}All 5 passes — pass 1 is the card above pass itotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 printf("total=%d ", total);
11 printf("total=%d\n", total15);12 return 0;13}outputtotal=15
Follow the Loop
limitstarts at4.totalstarts at0.- The loop adds
1, then2, then3, then4. totalbecomes10.- The program prints
total=10. | limit | numbers added | total | | --- | --- | --- | | 3 | 1, 2, 3 | 6 | | 4 | 1, 2, 3, 4 | 10 | | 5 | 1, 2, 3, 4, 5 | 15 |
Exercise: loops.c
Reproduce total=10, then use the pinned limits 3 and 5 to predict each total.