for and while in C programming language
In programming it's very common task to repeat some block of code many times. It can be achieved with loops in any programming language. Of course C language has loops too: for and while.
for loop in C language
for loop is used when we know how many times we want to repeat the block of code.
10 strings of "Hello World" will be printed on the screen. In the brackets we see three statements:
- int i = 0 - creates variable i and initializes it with 0. Such variables are called counters. This statement is executed only one time - before starting of the loop.
- i < 10 - condition. If it's true, the body of the loop will be executed. This condition is examined at each iteration of the loop.
- i++. Here we see new operator for us ++, it's called increment - it increases the variable by one. This statement is executed at the end of each iteration.
Let's follow all process. When processor sees the for loop it executes the first statement in brackets - initializes the counter, in our case i will be equal 0. Then it checks condition, at this time it's true: 0 is less than 10, so processor executes the code in braces. At the end it increases the i and returns to the top to check the condition. At this time it's true too - 1 is less than 10. Same process repeats... At the end of last iteration i becomes 10 and condition becomes false so processor jumps to next line after the body of for.
As I wrote above, for loop is better to use for situations when it's known how many iterations there will be.
while loop in C programming language
while loop executes it's body while the loop condition returns true. With while loop we can create infinite loop (it's very often practice).
It's not very useful piece of code. It just prints "Hello World" infinitely. We'll see more useful example of infinite loop a bit later.
We can simulate the for loop with while.
This code does the same as for loop above. In some kind while loop is more versatile.
do...while loop in C
There is additional form of while loop in C programming language:
The difference between while and do...while is that do...while will be executed at least one time no matter the condition. In this example the body of the loop is executed, then condition is checked - it's false and process jumps to next line of code.
With the keyword continue we can skip the rest part of loop body and return to the beginning. In case of for, the counter will be increased.
break keyword allows to stop the execution of the loop. Let's examine the example:
Program will ask the user to input the direction until he input 'n', 'e', 's' or 'w'. In that case the break statement will stop the loop. You can only use break for such purpose with if condition, in switch it will stop only the switch itself.
That's it for today