| This article is a stub. It may be incomplete, unfinished, or have missing parts/sections. If the article can be expanded, please do so! There may be suggestions on its talk page. (April 2025) |
This tutorial describes loops in C and compares them to loops in Scratch.
Loops
There are three different types of loops in C; namely for, while, and do while.
For
The for loop has three parts: the initialization statement, the continue condition, and the repeated statement. A for loop can look something like this:
# include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
printf("Iteration number %d\n", i);
}
}That code should print out "Iteration number 0", "Iteration number 1", and so on until "Iteration number 9". This is similar to the following code in Scratch:
when gf clicked set [i v] to (0) repeat until <not <(i) < (10)>> say (join [Iteration number ] (i)) for (1) seconds change [i v] by (1) end
While
A while loop has the following format:
while (condition) {
// do something
}A while loop is equivalent to the following in Scratch:
repeat until <not<condition :: grey>> ... end
A while loop starts by checking if the condition is met. If the condition is met, the code inside the brackets is executed; once the code is done executing, the whole process repeats. If not, it skips over the loop entirely.
Endless
A while loop can be used like this, creating an endless loop:
# include <stdio.h>
int main(void) {
while (1) {
printf("Infinite loop\n");
}
}
It works by always meeting the loop condition, making the while loop loop infinitely. The equivalent in Scratch is:
when gf clicked forever say [Infinite Loop!]
Do While
A do while loop has the following syntax:
do {
// inner code
} while (condition)The do while loop always runs the code inside the loop once. Then, it works like a while loop. The equivalent in Scratch is:
move (10) steps repeat until <not <condition::grey>> move (10) steps