OverIQ.com

The while loop in C

Last updated on July 27, 2020


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

printf("hello\n");

But what if we want to print it 100 or 1000 times. Of course, writing the same statement 100 times or 1000 times would be insane. Using loops we can solve this kind of problem easily. C provides three types of loops.

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

The while loop #

Syntax:

1
2
3
4
5
6
while(condition)
{
    // body of while loop
    statement 1;
    statement 2;
}

Just like the if-else statement, the while loop starts with a condition. First, the condition is evaluated, if it is true then the statements in the body of the while are executed. After executing the body of the while loop, the condition is checked again, if it is still true then once again statements in the body of the while are executed. This process keeps repeating 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 between 1 to 100:

Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#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 i by 1
    }

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

Expected Output:

1
2
3
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 5, 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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;   // get the last digit of n
        sum += remainder;     // add the remainder to the sum
        n /= 10;              // remove the last digit from n
    }

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

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

Expected Output: 1st run:

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

2nd run:

1
2
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.

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

2nd step: #

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

1
2
3
sum += remainder
sum = sum + remainder
sum = 3

3rd step: #

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

1
2
3
n /= 10
n = 123 / 10
n = 12

2nd iteration #

n = 12

1st step: #

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

2nd step: #

1
2
3
4
sum += remainder
sum = sum + remainder
sum = 3 + 2
sum = 5

3rd step: #

1
2
3
n /= 10
n = 12 / 10
n = 1

3rd iteration #

n = 1

1st step: #

1
2
3
remainder = n % 10;
remainder = 1 % 10
remainder = 1

2nd step: #

1
2
3
4
sum += remainder
sum = sum + remainder
sum = 5 + 1
sum = 6

3rd step: #

1
2
3
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.