Jan 22 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:

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:

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):