while and do…while Loop


Loop

In programming, a loop enables the execution of a block of commands over and over again until a specific condition is met. In this instructional guide, we will explore the while loop and the do.. while loop tutorials, concepts and examples.

Advantages of Loop

  • No need to write code again and again
  • This reduces errors
  • It provides code reusability
  • Improve readability
  • Traverse over element of data structures

C programming has three types of loops:

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

In the previous tutorial, we learned about for loop and nested for loop. In this tutorial, we will learn about while and do..while loop tutorials.


while Loop

A while loop is a control flow statement that allows you to execute a block of code repeatedly as long as a certain condition is true.
Note: While loop is also called Pre-tested loop.

The basic syntax of a while loop in C programming is as follows:

Syntax

while (condition) {
  // code to be executed repeatedly while the condition is true
  // this code block is also known as the loop body
  // it can contain any valid C statements
}


Here’s, how the while loop works?

  • condition is an expression that is evaluated before each iteration of the loop. If the condition is true, the loop body is executed. If the condition is false, the loop is terminated, and the program continues with the next statement after the loop.

  • The curly braces {} enclose the loop body, which holds the code executed repeatedly as long as the condition remains true.

  • Inside the loop body, you can have any valid C statements, such as variable declarations, assignments, function calls, and conditional statements. You can also have other loop constructs like nested loops and break/continue statements.

Important! Note: It’s important to include code within the loop body that eventually changes the condition, so that the loop doesn’t run indefinitely. Otherwise, it would result in an infinite loop, and the program would keep executing the loop body forever.


For instance:

#include <stdio.h>
int main() {
    int count = 0;
    
    while (count < 5) {
        printf("Count: %d\n", count);
        count++;
    }
    
    return 0;
}


Here’s how it the for loop works:

  1. The program starts by declaring and initializing the variable “count” to 0.

  2. The while loop is set up with the condition “count < 5”. This means that the loop will execute as long as the value of “count” is less than 5.

  3. The loop uses the printf function to print the current value of “count” along with a newline character.

  4. After printing the value, the “count” variable increments by 1 using the “count++” statement.

  5. The loop repeats from step 2 until “count” becomes equal to or greater than 5.

  6. Once “count” is no longer less than 5, the while loop terminates, and the program reaches the “return 0;” statement, indicating successful completion of the main function.

In summary, the program prints the values of “count” from 0 to 4 and then stops, as the loop condition “count < 5” becomes false when “count” becomes 5.

When you run this code, the output will be as follows:

Output

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

As you can see, the loop executes five times as it starts with count at 0 and increments it by 1 in each iteration. Once count becomes 5, the condition count < 5 becomes false, and the loop terminates.


do…while Loop

The do…while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Note: So, the do…while loop is also called Post-tested loop.

The basic syntax of a do…while loop in C programming is as follows:

Syntax

do {
    // Code block to be executed
} while (condition);


Here’s how it the for loop works?

  1. The keyword “do” initiates the loop and mandates the execution of the code block that follows, irrespective of the condition, for at least one iteration.

  2. The loop body, denoted by the curly braces { … }, contains the actual code that repeats execution as long as the condition remains true.

  3. while (condition): This part of the syntax defines the loop condition. After executing the code block inside the “do” portion, the loop will check the “condition.” If the condition evaluates to true, the loop will repeat and execute the code block again. If the condition evaluates to false, the loop will terminate, and the program will continue with the next statement after the “do-while” loop.

Important! Note: It’s essential to ensure that the loop condition has a way to become false; otherwise, the loop may turn into an infinite loop, causing the program to run indefinitely.

For instance:

#include <stdio.h>
int main() {
    int count = 1;

    do {
        printf("%d ", count);
        count++;
    } while (count <= 5);

    printf("\n");
    return 0;
}


Here’s, how the do…while loop works?

  1. We declare and initialize an integer variable count to 1. This variable will keep track of the numbers we want to count.

  2. We use a “do-while” loop to print the numbers from 1 to 5. The loop body contains the following statements:

    a. printf(“%d “, count);: This statement prints the current value of count followed by a space. The %d is a format specifier used to display an integer value. Initially, count is 1, so it will print “1 “.

    b. count++;: This statement increments the value of count by 1. After printing 1, count becomes 2 in the first iteration.

  3. The loop condition is while (count <= 5). This condition checks whether the value of count is less than or equal to 5. If the condition is true, the loop body will execute again; otherwise, the loop will terminate.

  4. The “do-while” loop guarantees that the loop body will execute at least once, even if the loop condition is false from the beginning. In this example, the loop will continue to execute as long as count is less than or equal to 5.

  5. The loop will execute five times, printing the values of count from 1 to 5, each separated by a space.

  6. After the loop, we print a newline character using printf(“\n”) to move to the next line for better output formatting.

  7. Finally, we return 0 from the main function to indicate successful program execution.

Output

1 2 3 4 5

The output shows the numbers from 1 to 5, each separated by a space. This is because the loop iterates five times, and count goes through the values 1, 2, 3, 4, and 5 in each iteration.