while Loop

Finally, we can talk about something more interesting! Loops are statements which continuously repeat execution of some code, while the condition is true (that is, does not evaluate to zero).

The most basic loop in C is called while, and can be written as

while (condition)
	...

As with if, the ... above means either a single statement ending with a semicolon, or a compound statement: curly braces with some other statements inside.

Let's write a simple while loop. By the way, that you can combine variable declaration and its first assignment: instead of writing int i; and then i = 5;, you can write int i = 5;:

#include <stdio.h>

int main() {
	int i = 5;

	while (i > 0) {
  	printf("i = %d\n", i);
  	i = i - 1;
	}

	return 0;
}

Run the code. It should print all numbers from 5 to 1 and stop when the value of i becomes zero, because the condition i > 0 becomes false at that point.

It often takes time to understand what i = i - 1 means, because if you have a lot of experience solving math equations, this line just does not make sense. Let me remind you that = is not a comparison, but an assignment, so this line takes the value to the right of =, which is i - 1, and assigns it to i, therefore decreasing i by 1.

Another useful thing is c = c + 1. If you assign c = 0; before the while loop, and place c = c + 1; in a loop, c will count how many times the loop has executed – or, as we say, how many iterations it performed. We call such variables a counter, and you will need to create one on the next page!

You can do it with any expression: i = i + 2 will increase the value of i by 2, while x = x / 10 for int x will divide x by 10 as a whole number (dropping the remainder) and assign the result to x. Let's look closer at this example on the next page!