Loops and Collatz
for and while loops with break and continue words, plus a Collatz step counter.
+ <stdio.h>
f main()
total:=0
for i := 1; i < 11; i++
total += i
printf("sum 1..10 = %d\n", total)
n:=27
steps:=0
while n != 1
n = n % 2 ? 3 * n + 1 : n / 2
++steps
printf("collatz(27) takes %d steps\n", steps)
< 0
#include <stdio.h>
int main(void) {
int total = 0;
for (int i = 1; i < 11; i++) {
total += i;
}
printf("sum 1..10 = %d\n", total);
int n = 27;
int steps = 0;
while (n != 1) {
n = n % 2 ? 3 * n + 1 : n / 2;
++steps;
}
printf("collatz(27) takes %d steps\n", steps);
return 0;
}
Output
sum 1..10 = 55
collatz(27) takes 111 steps
What it shows
loops, break, continue