for loops
Read · 1 of 4
Three parts in one line
for (int i = 1; i <= 5; i++) { … } packs the start (i = 1), the condition (i <= 5) and the step (i++) into one line. It's a while loop that's harder to get wrong.
Use it when you know how many times to repeat.
Read this lesson as text
Counting loops in one line: start, condition, step.
Three parts in one line
for (int i = 1; i <= 5; i++) { … } packs the start (i = 1), the condition (i <= 5) and the step (i++) into one line. It's a while loop that's harder to get wrong.
Use it when you know how many times to repeat.
Counting down
#include <stdio.h>
int main() {
for (int i = 10; i > 0; i -= 3) {
printf("%d ", i);
}
printf("\n");
return 0;
}What does this print (spaces included)?
- 10 7 4 1
- 10 7 4
- 10 7 4 1 -2
Show the answer
10 7 4 1 10, 7, 4 and 1 are all above 0. Next would be -2, which fails i > 0.
Exercise: Times table
Read n and print its table from 1 to 10, one line each: 7 x 1 = 7 … 7 x 10 = 70.
Exercise: Factorial
Read n (0 to 20) and print n! = 1 × 2 × … × n. 0! is 1.
20! is huge: use long long and print it with %lld.