for Loop

You saw loops like this one multiple times on previous pages:

i = 0;
while (condition) {
	...
	++i;
}

For example, if we just want to print all numbers between 0 and 10, not including 10:

#include <stdio.h>

int main() {
	int i = 0;
	while (i < 10) {
		printf("%d\n", i);
		++i;
	}
	return 0;
}

This pattern is seen so often that there is a special type of loop in C (and many other languages!) created specifically to accommodate it. Let's look at it closely:

INITIALIZATION;				/* e.g. i = 0;             */
while (CONDITION) {		/* e.g. i < 10             */
	BODY;								/* e.g. printf("%d\n", i); */
	ADVANCEMENT;				/* e.g. ++i                */
}

In C, the above loop can be rewritten using this new syntax:

for (INITIALIZATION; CONDITION; ADVANCEMENT)
	BODY;

The same printing of all numbers from 0 to N with the for loop looks like this:

#include <stdio.h>

int main() {
	int i;

	for (i = 0; i < 10; ++i) {
		printf("%d\n", i);
	}

	return 0;
}

Note that the { } braces are not required in this case, because there is just one statement, printf("%d\n", i);, inside the for loop, but I prefer to use the braces even in this case.

The for loops works exactly as the while loop, but with some extra statements executed. First, the INITIALIZATION statement is executed; in our example, it's the assignment i = 0. It will be executed just once. Then it works just like the while loop with the condition i < 10, but after each iteration, the ADVANCEMENT statement ++i will be executed.

The fun thing about C for loops is that each part can be omitted. No initialization means, well, no initialization:

int i = 0; /* we can initialize it this way, it's OK! */

for ( ; i < 10; ++i) { /* empty initialization */
	...
}

We can omit the advancement statement too, e.g. if we want to handle it in the loop body:

for (i = 0; i < 10; ) { /* empty advancement */
  ...
	++i; /* we can do it here if we want */
}

We can even omit the condition! That makes the for loop infinite, unless we break; from it at some point.

for (i = 0; ; ++i) {
	printf("%d\n", i);
	if (i >= 10) { /* we still want to break from it,
                    otherwise it just loops forever */
		break;
	}
}

And, of course, we can just omit everything, leaving an empty ; as a loop body:

for ( ; ; )
	;

Well, this is just an infinite loop. It will heat up your CPU and never exit, unless you stop the program.

In the execution blocks here on this website, there's a timeout of 10 seconds for each execution, so it's not a big deal if you happen to execute an infinite loop. Do it now, no worries!

int main() {
	for ( ; ; )
		;
	return 0;
}

(note: no #include <stdio.h> because I'm not using any input or output functions here)

Did you see the timeout after 10 seconds?

On the real computer, you probably need to press Ctrl+C to stop a program that "hangs".