Site icon DataFlair

Do While Loop in C

do while loop in c

Loops are an indispensable tool in programming, enabling us to repeatedly execute blocks of code for iterative tasks.

In C, we have several loop constructs at our disposal, including the versatile do-while loop. Unlike the for and while loops, the do-while loop ensures the loop body is executed at least once before checking the loop condition. This unique structure makes do-while loops ideal for situations that require one guaranteed run of the loop before potentially breaking out of the iteration.

Understanding the Do While Loop in C

The do-while loop in C executes a code block once initially and then repeats the loop body continuously while a condition remains true.

Its syntax follows:

do {
// code block
} while (condition);

Notice that the loop condition is evaluated after the loop body, unlike the while loop. This means the code block will run at least once regardless of the condition’s value. The condition is still critical since it determines if the looping continues beyond the initial execution.

#include <stdio.h>

int main() {
  int count = 1;

  do {
    printf("Dataflair\n");
    count++;
  } while(count <= 4);
  
  return 0;
}

Output:

Dataflair
Dataflair
Dataflair
Dataflair

How the C Do While Loop Works?

We can visualize the operation of a do-while loop in C by thinking of it as a rollercoaster ride. You get strapped into your seat on the rollercoaster (the initial unavoidable execution), and only after completing the ride do you get to decide if you want to go again based on whether you met your thrill quota (the loop condition). If you’re still thirsty for adrenaline, you strap yourself in for another round. You keep reading until you’ve had your fill of excitement.

The do-while loop follows a similar predefined sequence:

Do While Loop Structure in C

Let’s explore the anatomy of a do-while loop in more detail:

Properties of the C Do While Loop

Common Use Cases

Menu-Driven Programs

Do-while loops shine in interactive, menu-driven programs that require displaying a menu, accepting user input, processing the input, and repeating continuously. The menu choices are always shown at least once before checking if the user wants to quit.

Input Validation

When accepting input like age, we can use a do-while loop to validate if the input is sensible before using it programmatically. The validation code executes at least once, preventing progression until the input has been verified.

Data Processing

In applications like data logging that need to run until a specific event occurs, a do-while loop runs continuously until the terminating condition is met. The data is processed in each iteration until logging should stop.

Best Practices

Example Code Walkthrough

Let’s look at some do-while loop examples to demonstrate their usage.

Counting Down

int count = 5;
do {
  printf("%d\n", count);
  count--; 
} while (count > 0);

Output:

5
4
3
2
1

Factorial Calculation

int num = 5, factorial = 1;

do {
  factorial *= num;
  num--;
} while (num > 1);

printf("Factorial of 5 is %d", factorial);

Output:

A factorial of 5 is 120

Menu-Driven Program

int choice;

do {
  printf("Menu \n");
  printf("1. Option 1\n");
  printf("2. Option 2\n"); 
  printf("3. Quit\n");

  printf("Enter your choice: ");
  scanf("%d", &choice);
  
  if(choice >=1 && choice <= 3) {
    if(choice == 3) 
      break; 
    else 
      printf("Perform option %d tasks\n", choice); 
  }
  else {
    printf("Invalid choice. Try again.\n");
  }
} while(1);

printf("Exiting program...");

Output:

Menu
1. Option 1
2. Option 2
3. Quit

Enter your choice: 4
Invalid choice. Try again.

Menu
1. Option 1
2. Option 2
3. Quit

Enter your choice: 2
Perform option 2 tasks

Menu
1. Option 1
2. Option 2
3. Quit

Enter your choice: 3
Exiting program…

This showcases how a do-while loop can create a reusable menu with input validation.

Nested Do-While Loops in C

Like other loop statements in C, do-while loops can also be nested to create complex iterative logic. A nested do-while places one do-while loop within the body of another do-while loop.

The inner loop executes to completion for every single iteration of the outer loop. This allows you to add layers of processing logic.

Let’s look at examples to understand this better.

Printing a Pattern

Every time the outer loop iterates in this nested loop, a pattern of increasing size is printed.

int rows = 5;
int i = 1;

do {
  int j = 1; 
  do {
    printf("*");
    j++; 
  } while(j <= i);
  
  printf("\n");
  i++;

} while(i <= rows);

Output:

*
**
***
****
*****

The inner loop handles printing the stars and increments j. The outer loop increments i to control the number of rows.

Debugging and Common Mistakes

Like any loop, do-while loops can cause headaches if not structured properly. Follow these debugging tips:

Difference between while and Do while Loop in C

Feature while loop do…while loop
The test condition is checked Before the loop body is executed After the loop body is executed
Execution of loop body Not executed if the condition is false Executed at least once, even if the condition is false
Type of loop Pre-tested or entry-controlled loop Post-tested or exit-controlled loop
Semicolon Not required Required at the end

Conclusion

The C do-while loop is a versatile tool for writing conditional loops requiring one assured pass before potentially breaking out of the iteration. Its unique structure opens up possibilities for creating menu-driven programs, validating input, and other use cases benefiting from an initial loop execution. By learning how and when to leverage the do-while loop, you expand your ability to craft efficient C programs.

Exit mobile version