C while loop

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.

Advertise on this site. I promise you will like the rates :)

C while loop - pre-condition flow chartIf the condition is false the first time, the statements in the body won't execute at all

Syntax

The syntax is quite simple.

while(<Condition>)
{
    ...
       Execute statements
    ...
}

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.

    In C, 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.

    while(<Condition>)
        Execute statement

C while loop examples

Printing the numbers from 1 to 10

int main(void)
{
    int i = 1;
    while(i <= 10)
    {
        printf("%d\n", i);
        ++i;
    }
    return 0;
}

Infinite loop

    To create an infinite loop is easy. Just put a non zero constant in the condition.

void infiniteLoop(void)
{
    while(1)
    {
        Infinite stuff goes here
    }
}

You can use this technique in some specific situations. Then you will end the loop with a break, return or goto statement. 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.

Reading a file

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", "r");
int symbol;
if (fp == NULL)
{
    perror("Cannot open file numbers.txt");
    return;
}
else
{
    while ((symbol = fgetc(fp)) != EOF)
    {
        printf("%c", symbol);
    }
    fclose(fp);
}                                                                 

The source code from all of the examples is available in our GitHub repository. You can also download the code of the examples here: c-while-loop.zip

See also:

    This article is part of two tutorials: Basic C tutorial and keywords in C. Continue accordingly:

Previous lesson: loops in C

Next lesson: do..while loop

Previous keyword: volatile

Next keyword: This is the last keyword - go back to all c keywords

   Search this site: