A for loop in C is a control flow statement for repeated execution of a block of code. Very similar to Python, but with a different syntax.
The syntax of a for loop in C consists of three main parts:
There is no "for each" (iterables) in C. For example, there is no way to do:
for car in cars:
print(car)
Instead, we have to iterate over the numbers of indices in a list, and then we can access the item using the index.
for (initialization; condition; final-expression) {
// Loop Body
}
for Loopint i = 0; for exampletrue, execute the body. If false, terminate the loopi is less than some value: i < 5; for examplei++ for example#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
// Prints:
// 0
// 1
// 2
// 3
// 4
Implement the print_numbers prototyped in exercise.h that takes a starting number and an ending number and prints all the numbers in that range inclusive (using a for-loop).