The while Loop

In the last tutorial, we learned the significance of loops in programming. I have also introduced you to the three types of loops provided in C programming. Now, let’s learn the while loop in detail.


Syntax and Structure

The while loop in C is one of the easiest and the fundamental loop type in C that allows us to repeat a block of code based on the condition it checks. Following is the syntax of the while loop in C:

while (condition) statement;

Let’s understand the syntax properly:

  • while:  this keyword marks the beginning of the loop and is mandatory.
  • condition:  an expression that evaluates to either true or false. 
  • statement:  this will execute as long as the condition remains true. 

As long as the condition remains true, the statement following the closing parentheses will execute repeatedly. 

The syntax allows us to add only one statement, but most often we may want to execute a bunch of statements repeatedly. For this, we can do a trick. We can use what is called a compound statement in C. 

A compound statement is a set of statements enclosed within curly braces. In C language, a group of statements enclosed within curly braces are considered as a single statement. So, technically, the above syntax can be replaced by the following:

while (condition) 
{
    // Bunch of statements to execute repeatedly
}

Now, we can execute a couple of statements repeatedly within the loop body.


How Does It Work?

There are three things involved in the successful execution of the while loop:

  1. Initialization (before the loop):  you typically declare and initialize a loop counter variable before the loop starts. 
  2. Condition:  the loop counter variable is utilized here and usually compared with some other value. If the expression evaluates to true, then the control transfers to the loop body immediately. Otherwise, the statement following the loop will execute.
  3. Increment/Decrement:  within the loop body, there can be either an increment or decrement statement that either increments or decrements the counter variable. This ensures that the condition eventually becomes false, terminating the loop.

So, in a nutshell

  • The counter variable is initialized.
  • The while condition is checked.
  • If the condition is true, the loop body will execute.
  • If the condition is false, the statement following the loop will execute.
  • Within the loop body, apart from the statements we want to repeat, there can be an increment or decrement statement that increments or decrements the counter variable.
  • The while condition is again checked, and the process repeats.

If the process is still unclear, the following flowchart will make it crystal clear:

Flowchart of the while loop

Example 1:  Printing the number from 1 to 10

#include <stdio.h>

int main() {
    int counter = 1; // counter variable initialization
    while (counter <= 10) { // condition checking
        printf("%d\n", counter);
        counter++; // incrementing the counter variable
    }
    return 0;
}

In this example program:

  • The variable counter is initialized to 1.
  • Then, the condition “counter <= 10” is checked. It evaluates to true.
  • The loop body will execute which means the “prinf()” function will display the current value of the counter variable which is 1 and then the counter is incremented by 1. Now, it becomes 2.
  • The condition “counter <= 10” is again checked. This time also the condition is true.
  • The loop body will execute, and in the same way, it continues to execute until the counter variable holds 11 which eventually makes the condition false, and terminates the loop.

Example 2:  Summing numbers until user enters 0

#include <stdio.h>

int main() {
    int sum = 0, number;

    printf("Enter the number (0 to stop): ");
    scanf("%d", &number);

    while (number != 0) {
        sum += number;
        printf("Enter the number (0 to stop): ");
        scanf("%d", &number);
    }
    printf("The sum is %d", sum);
    return 0;
}

Output:

Enter the number (0 to stop): 10
Enter the number (0 to stop): 20
Enter the number (0 to stop): 30
Enter the number (0 to stop): 40
Enter the number (0 to stop): 50
Enter the number (0 to stop): 0
The sum is 150

In this example,

  • The variable sum is initialized to 0 and the number variable is the counter variable which is not yet initialized. In the next step, we will ask the user to provide the value for the number variable.
  • Now, we are asking the user to enter the number which will eventually be stored in the number variable.
  • Let’s assume that the user has entered the number 10. Then, the while condition “number != 0” evaluates to true. This means the loop body will execute.
  • The statement “sum += number” will execute which is equivalent to “sum = sum + number”. The initial value of sum is zero, therefore, after execution of the statement, the variable sum will hold value 10.
  • Again, within the loop body, we are asking the user to enter the number. Let’s assume this time the user has entered 20.
  • The condition “number != 0” evaluates to true.
  • The statement “sum += number” will execute. The current value of sum is 10 and that of the number variable is 20. This means this time, the variable sum will hold value 30.
  • Again we ask the user to enter the next number. The process will continue this way until the user enters 0.
  • Once the user enters 0, the while condition becomes false and the statement following the while loop which is “printf(“The sum is %d”, sum);” will be executed. This prints the final value of the sum.

Common Mistakes and Best Practices

First, we will discuss what are some of the most common mistakes people make in the while loop and then we will proceed with some of the best practices which every programmer should follow.

Common Mistakes in while Loops

  1. Infinite loops:  if you forget to increment/decrement the loop counter variable, then the loop condition will never become false and the loop will run forever. In some cases, infinite loops are useful (we learn more about this in our upcoming tutorials) but mostly, we may need to terminate our loop through the loop counter variable.
  2. Incorrect condition:  the loop condition decides whether to enter or exit the loop. An incorrect condition may lead to unexpected behavior. It may be possible that the loop will run a number of times which was unexpected or we may not even enter the loop in the first place.
  3. Uninitialized loop variables:  never forget to initialize the loop counter variable. Doing so will lead to unexpected behaviors.
  4. Off-by-one errors:  make sure that the correct relational operator (==, != , <=, >=, <, >) is used in the loop condition. For instance, it may be possible that instead of less than or equal to (<=) operator, you may use less than (<) operator, and that would lead to off-by-one error as you will miss one value due to this.

Best Practices

  1. Clear and concise loop condition:  the loop condition must be easy to understand and should reflect the desired behavior.
  2. Meaningful variable names:  Choose names for your variables that make sense and describe what they are. For example, instead of just using “var = 30,” you could use “age = 30.” This makes it clear that the number 30 represents someone’s age.
  3. Comments:  add comments to explain the purpose of the loops you write. 
  4. Proper indentation:  improper indentation may lead to confusion and decrease the readability of your code significantly. Try to indent your code the way it should.

Level-Up Your Understanding

Question 1

What happens if the loop condition is always true?

Nothing happens
The loop will run forever
explanation

The loop will continue indefinitely, creating an infinite loop.

Question 2

Can the loop body be empty?

Yes
No
explanation

Yes, but it is generally not useful. When the loop body is empty, it will continue to run without doing anything. It does not make sense to write such a loop.

Question 3

Consider the following while loop:

while (n > 0) {
    d = n % 10;
    s += d;
    n /= 10;
}

What would be the final value of the variable s if n = 1234? (Assume that variables are declared already and the variable “s” has been initialized to 0)

10
20
30
40
explanation

The while loop calculates the sum of the digits of the number 1234. The while loop works as follows:
1. Initially, n is greater than 0, therefore the loop condition is satisfied and we will enter inside the loop.
2. n % 10 gives the last digit of the number which is 4. This number is now stored in the variable d.
3. Now, d is added to s, so the new value of s is 4.
4. n = n / 10 gives the quotient of the number 1234 which 123. This will be the new value of n.
5. Again, the condition is checked and satisfies.
6. This time d will hold the remainder of the number 123 which is 3 and s will hold the sum of 4 and 3 which is 7. 
7. In this way, all the digits of the number 1234 are added and the final value of sum will be 10. Hence, option (a).

Question 4

Consider the following code snippet:

num = 1;
while (num < 10) {
  printf("%d ", num);
  num++;
}

Does the above code snippet correctly produce numbers from 1 to 10?

Yes
No
explanation

No. This example demonstrates the off-by-one error concept which we have discussed earlier. In place of less than (<) operator in the while condition, we need less than or equal to (<=) operator to correctly produce numbers from 1 to 10.

Question 5

Determine the output of the following program:

#include <stdio.h>

int main() 
{
    int x = 0;
    while (++x < 5) {
        printf("%d", x);
    }
}
Infinite loop
12345
1234
No output
explanation

The pre-increment operator increments x before checking the condition. Initially, when x is 0, x is incremented to 1 and then the condition 1 < 5 is checked. As the condition is true, the printf() function will execute and print 1. The loop will continue to run until x becomes 5. At this point, printf() will not be evaluated, and hence the output will be 1234.

Your score is out of



Leave a comment

Leave a comment

Your email address will not be published. Required fields are marked *

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.