The while loop in C

Loops are used to execute statements or block of statements several times. For example, suppose we want to write a program to print "Hello" 5 times. One way to solve this problem is to write following statement 5 times.

printf("hello\n");

But what if we want to print it 100 or 1000 times. As you can see this is not ideal way to solve this problem. Using loops we can solve this kind of problem easily.

There are three loops in C language.

  1. while loop
  2. do while loop
  3. for loop

The while loop #

Syntax:

while(condition)
{
    // body of while loop
    statement 1;
    statement 2;
}

Just like if... else statement while loop starts with a condition. First, the condition is evaluated, if the condition is true then the statements in the body of the while are executed, again the condition is checked if it is still true then once again statements in the body of the while are executed. The statements in the body of the while will keep executing until the condition becomes false. Therefore you must always include a statement which alters the value of the condition so that it ultimately becomes false at some point. Each execution of the loop body is known as iteration.

The following program uses while loop to prints all even numbers from 1 to 100.

Example 1:

#include<stdio.h>

int main()
{
    int i = 1;

    // keep looping while i < 100
    while(i < 100)
    {
        // if i is even
        if(i % 2 == 0)
        {
            printf("%d ", i);
        }
        i++; // increment the number
    }

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96
98

How it works:

In line 6, we have declared a variable i and initialized it to 1. First, the condition (i < 100) is checked, if it is true. Control is transferred inside the body of the while loop. Inside the body of the loop, if condition (i % 2 == 0) is checked, if it is true then the statement inside the if block is executed. Then the value of i is incremented using expression i++. As there are no more statements left to execute inside the body of the while loop, this completes the first iteration. Again the condition (i < 100) is checked, if it is still true then once again the body of the loop is executed. This process repeats as long as the value of i is less than 100. When i reaches 100, the loop terminates and control comes out of the while loop.

Consider one more example:

Example 2:

The following program calculates the sum of digits of a number entered by the user.

#include<stdio.h>

int main()
{
    int n, num, sum = 0, remainder;

    printf("Enter a number: ");
    scanf("%d", &n);

    num = n;

    // keep looping while n > 0
    while( n > 0 )
    {
        remainder = n % 10; // take out the last digit of a number
        sum += remainder; // add the remainder to the sum
        n /= 10; // can also be written as n = n / 10
    }

    printf("Sum of digits of %d is %d", num, sum);

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

1st run:

Enter a number: 222
Sum of digits of 222 is 6

2nd run:

Enter a number: 456
Sum of digits of 456 is 15

How it works:

Let's say the user entered 123, then here are the steps to find the sum of digits.

1st iteration

n = 123

1st step

Take out the last digit of 123 by evaluating 123 % 10 and store the result in the variable remainder.

remainder = n % 10;
remainder = 123 % 10
remainder = 3

2nd step

add the number obtained in the last step to variable sum.

sum += remainder
sum = sum + remainder
sum = 3

3rd step

Now we don't need last digit of 123, so remove it by evaluating 123 / 10.

n /= 10
n = 123 / 10
n = 12

2nd iteration

n = 12

1st step

remainder = n % 10;
remainder = 12 % 10
remainder = 2

2nd step

sum += remainder
sum = sum + remainder
sum = 3 + 2
sum = 5

3rd step*

n /= 10
n = 12 / 10
n = 1

3rd iteration

n = 1

1st step

remainder = n % 10;
remainder = 1 % 10
remainder = 1

2nd step

sum += remainder
sum = sum + remainder
sum = 5 + 1
sum = 6

3rd step

n /= 10
n = 1 / 10
n = 0

When n reaches 0 while condition becomes false and control comes out of the while loop. Hence the sum of digits of 123 is 6.