Learn the C Programming Language!
Think of the for loop as a more bulky version of the while loop. Here is the generic for loop:
for(set value; check; increment) {
do something;
}
This may seem confusing, so let’s put it into practice. Let’s rewrite the squares.c code from earlier, this time with a for loop instead of a while loop.
#include <stdio.h>
/* squares.c: version 2 */
main() {
int i;
for(i = 1; i < 21; ++i)
printf("%d\n", i^2);
}
Compare this code to the one in the previous section. Notice we cleaned up the code quite a bit: The following two lines have been removed and put into the condition of the for loop:
i = 1;
i++;
Also, you’ll notice I replaced the condition i ≤ 20 with i < 21. This only works because i is going up by one; later you will learn that there are non-integer data types that we can increment by 0.5 at a time.
Another thing you may have noticed with the for loop:
for(i = 1; i < 21; ++i)
printf("%d\n", i^2);
I didn’t include any curly braces! You may be thinking, “What a hypocrite! He told us that almost every bracket in C has a corresponding closing bracket!” First of all, I said almost. Second, I technically never put an opening curly brace; in fact, I don’t need to! If a for loop is less than two lines (including the condition) you don’t need curly braces. So, I can simplify the following expressions:
for(i = 0; i < 3; i++) {
printf("asd\n");
}
for(i = 0; i < 3; i++) {}
into:
for(i = 0; i < 3; i++)
printf("asd\n");
for(i = 0; i < 3; i++);
Note: What do you think the second statement does?