In C while loop is the most basic loop. It repeats a statement while the condition is true. It is a pre-condition loop, because the condition is checked before the body of the loop.
The syntax is quite simple.
The condition could be any value or expression that could be evaluated. Unlike the for loop, here the condition cannot be empty. The loop will repeat while the condition is true.
a true value is anything that is different from 0 and ‘\0’.
Once the condition is evaluated as false, the loop stops. Then it transfers the control of the program to the first statement after the loop’s body.
Note that, if the body of the loop contains only one statement, you can omit the curly brackets.
int i = 1;
while(i <= 10)
To create an infinite loop is easy. Just
put a non zero constant in the condition.
Infinite stuff goes here
Note that this should be used rarely. It is considered bad coding practice to use infinite loops. Use them only if you have a good reason to do it; for instance if it makes the code easier to read.
One common usage of the c while loop is to read a file. In the next example we open the file “numbers.txt” for reading and loop until we reach the end of file. We also print each symbol that we read. So what the example does is to open a text file and print it in the console.
FILE *fp = fopen("numbers.txt",
if (fp == NULL)
perror("Cannot open file numbers.txt");
while ((symbol = fgetc(fp)) != EOF)
You can download the code of the examples here: c-while-loop.zip