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.

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:

Just like ifelse 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:

Expected Output:

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.

Expected Output:

1st run:

2nd run:

How it works:

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

1st iteration

1st step:

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

2nd step:

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

3rd step:

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

2nd iteration

1st step:

2nd step:

3rd step:

3rd iteration

1st step:

2nd step:

3rd step:

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.

Leave a Comment