A while
loop is used to execute a piece of code while a condition is true. The while
loop is to be used when a block of code is to be executed a variable number of times.
For example the code shown gets the user input, as long as the user inserts numbers which are not 0
. If the user inserts 0
, the while condition is not true anymore so execution will exit the loop and continue on to any subsequent code:
int num = 1;
while (num != 0)
{
scanf("%d", &num);
}