Programming in C: While Loop

During the last tutorial we looked at for loop, now we will look at while loops. While loops are a simplified version of a for loop, instead of having three conditions it only has one.

The only condition it has is the conditional statement, which if true the block of code will continue to repeat, if false it will exit the loop and continue with the rest of the program. Here is the general structure of a while loop:

while (condition)
{
/* block of code to execute. */
}

Here is an example of a while loop in practice:

#include <stdio.h>

int main()
{ 
int x = 0; 

while ( x < 10 ) 
{ 
printf( "%d\n", x );
x++;
}
return 0;
}

Another type of while loop is a do..while loop which allows you to have the same functionality of a while loop, but the block of code will be executed at least once. Here is the general format of a do..while loop:

do 
{
 /* block of code to execute. */
} while (condition);

Here is an example of a do..while loop in practice:

#include <stdio.h>

int main()
{
int x = 0;

do 
{
/* Notice "Hello World!" will be printed at least once, then the conditionis checked. */
printf( "Hello, world!\n" );
} while ( x != 0 );
return 0;
}

Note the semi-colon after the while statement, in the do..while loop. That semi-colon is necessary.

Break and Continue

Break and continue are two key words used in C, which do exactly what you think. Break will exit, or break out of, the loop you are in. Continue will continue executing the block of code in the loop. Here is an example to illustrate break and continue (assume the required code is declared above, I will not show it for simplicity):

for (player = 1; someone_has_won == FALSE; player++)
{
 if (player > total_number_of_players)
 {
player = 1;
 }
 if (is_bankrupt(player))
 {
continue;
 }
 take_turn(player);
}

Apple Says it Will Fix iOS 7's 'White Screen of Death'

YouTube Launches New Video Quality Report in Canada