The while loop in C

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.

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:

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:

Expected Output:

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.

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 the variable sum.

3rd step:

Now we don’t need the 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

%d bloggers like this: