Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Do While Loop in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Looping in programming is like repeating a song you love; it plays over & over until you decide to stop. In C programming, there's a special loop called do…while that plays the song at least once even before you check if you want to hear it again. 

Do While Loop in C

This article is all about understanding this loop, how to write it, and when to use it. We'll go through its structure, see it in action with examples, and even compare it to other loops to spot the differences. 

What is do…while Loop in C?

In C programming, a do…while loop is a way to repeat some code in your program. Imagine you have a task you need to do at least once but maybe more, depending on something. That's what do…while loop does. It makes sure the task is done once first. Then, it looks at something, like a condition or a rule, to decide if it should do the task again.

It's different from other loops because it does the task first before checking if it should keep going. This is really handy when you know you need to do something at least once but you're not sure how many times you'll need to repeat it.

For example, if you're making a program where someone enters a password, you want to ask them for the password at least once. Then, after they enter it, you check if it's right. If it's not right, you ask them again. The do…while loop is perfect for this because it makes sure you ask for the password at least once and then keeps asking until the right one is entered.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of do…while Loop in C

The way you write a do…while loop in C is pretty simple. It has a specific structure you follow to tell the computer what you want to do. Here's how it goes:

do {
    // Your code here
} while (condition);


First, you write the word do, then put curly brackets {}. Inside these brackets, you write the code you want to repeat. After the curly brackets, you write while, followed by a condition in parentheses () and a semicolon ; at the end.

The "condition" part is like a question that has a yes or no answer. If the answer is yes (which in programming we call "true"), the loop goes back and does the code inside the curly brackets again. If the answer is no (or "false"), the loop stops, and the computer moves on to whatever comes next in your program.

So, in short, the do…while loop says to the computer: "Do this code at least once; then, as long as this condition is true, keep doing it."

How to Use do…while Loop in C

Using a do…while loop in C is about doing a task first and then checking if you need to do it again. It's perfect for when you know you must do something once, but after that, it depends on a condition.

Here's a step-by-step on how to use it:

Start with do

This tells your program that you're starting a do…while loop.

Write your task

Inside curly brackets {}, put the code for the task you want to do. This can be anything from printing a message, doing calculations, to reading user input.

Check your condition

After the curly brackets, write while followed by a condition in parentheses (). This condition is checked after the task is done.

Repeat or end

If the condition is true, your program goes back and does the task again. If it's false, the loop ends, and the program moves on.

For example, if you want to keep asking a user for a number until they enter -1, your do…while loop would look like this:

int number;
do {
    printf("Enter a number (-1 to exit): ");
    scanf("%d", &number);
    // You can do something with the number here
} while (number != -1);


This loop will ask for a number, do something with it, and keep asking until the user enters -1. The important part is, it asks at least once, no matter what number is entered first.

How does the do…while Loop work?

The do…while loop in C programming does its job in a simple way. First, it does the task you wrote inside the loop without asking any questions. Then, after the task is done, it looks at the condition you set. If the condition says "yes," the loop goes back and does the task again. If the condition says "no," the loop stops and the program moves on to do other things.

This loop is like a promise that the task will be done at least once. After the first time, the decision to repeat depends on the condition you write. This condition is checked after the task is done each time. So, the loop keeps running as long as the condition keeps saying "yes."

Here’s a closer look at each step:

  • Do the task: The code inside the loop runs first, no matter what.
     
  • Check the condition: After the task is done, the loop looks at the condition you wrote.
     
  • Decide: If the condition is true, the loop repeats the task. If it's false, the loop ends.

C do…while Loop Flowchart

A flowchart for a do…while loop in C helps you see how the loop works with simple shapes and arrows. Think of it as a map that guides you through the steps of the loop.

  • Start: This is where the loop begins.
     
  • Do the Task: There’s a box that represents the task you want to do. This is the code inside the do…while loop. The loop does this task first without checking anything.
     
  • Condition Check: After the task, there’s a diamond shape where the loop checks the condition you wrote. This diamond asks a yes or no question based on your condition.
     
  • Repeat or Exit: If the answer to the condition is yes, an arrow goes back to the task, and the loop does it again. If the answer is no, an arrow points out of the loop, and the program moves on to do other things.

Nested do…while Loop in C

A nested do…while loop in C is when you have a do…while loop inside another do…while loop. It's like putting one loop inside another. You use this when you need to do a set of tasks that also need repeating, but within another task that's repeating too.

Here's how it works:

  • Outer Loop: This is the first do…while loop you start with. It has its own task and condition.
     
  • Inner Loop: Inside the outer loop's task, you put another do…while loop. This inner loop also has its task and condition.
     
  • Run Inner Loop: When the outer loop does its task, it runs the inner loop. The inner loop keeps doing its task and checking its condition until its condition says no.
     
  • Check Outer Loop Condition: After the inner loop is done, the outer loop checks its condition again. If the outer condition is still yes, it does its task again, which includes running the inner loop again.
     

This setup lets you handle more complex situations where you need to repeat actions within other repeated actions. For example, if you're going through a list and for each item in the list, you need to check another list, nested loops are what you need.

Example

Let's look at a simple example of a nested do…while loop in C. Suppose you're creating a program that asks a user to enter numbers for two separate lists. For each list, the user can enter as many numbers as they want until they enter -1, which moves them to the next list or ends the input process.

Here's how you can use a nested do…while loop for this task:

  • C

C

#include <stdio.h>

int main() {

   int num, list = 1;

do {

       printf("List %d (enter -1 to switch to next list or finish):\n", list)

   do {

        scanf("%d", &num);

         if (num != -1) {

          printf("  Number %d added to List %d\n", num, list);

        }

   } while (num != -1);

  list++;  // Move to the next list

   } while (list <= 2 && num != -1);  // Allows for two lists, stops if -1 entered in the first list

printf("Finished entering numbers for both lists.\n");

  return 0;

}

Output

Output

In this code:

  • Outer Loop: Manages the lists. It starts with List 1 and moves to List 2 after entering -1.
     
  • Inner Loop: Takes the numbers for each list. It keeps asking for numbers until -1 is entered, indicating the end of the current list.
     
  • List Counter: list variable tracks which list the numbers are being added to. It increases when moving to the next list.
     
  • Ending Condition: The outer loop checks if the process should move to the next list or finish (after 2 lists or if -1 is entered in the first list).
     

This example shows how nested do…while loops can handle multiple layers of repetition, like filling multiple lists with user inputs in this case.


Examples of do…while Loop in C

To really understand how do…while loops work in C, let's look at a simple example. Imagine you're writing a program that asks users for a number until they enter a specific number to stop. We'll use the number -1 as the signal to stop.

Here's how you could write this:

  • C

C

#include <stdio.h>

int main() {

   int number;

 do {

       printf("Enter a number (-1 to stop): ");

       scanf("%d", &number);

       // You can add actions here to do something with the number

   } while (number != -1);

 printf("You entered -1, so the loop has ended.\n");

 return 0;

}

Output

Output

In this example:

  • Start the Loop: The program starts the do…while loop without checking any condition first.
     
  • Do the Task: It asks the user to enter a number and stores that number in a variable called number.
     
  • Check the Condition: After getting the number, the loop checks if it's -1. If it's not -1, the loop repeats. If it is -1, the loop ends.
     
  • End of Loop: The program prints a message saying the loop has ended and then finishes.
     

This example shows the do…while loop in action, doing a task at least once and repeating it based on a condition checked after the task.

Difference between while and do…while Loop in C

In C programming, both while and do…while loops are used to repeat tasks, but they have a key difference in how they start their processes.

When They Check Conditions:

while Loop: It checks the condition before doing the task. If the condition is false right from the start, the loop's task won't run even once.

do…while Loop: It does the task first and checks the condition after. This means the loop's task will always run at least once, no matter what the condition is initially.

Usage

  • Use a while loop when you're not sure if the task should run even once. The condition is checked first, so it's possible the task inside the loop might never run.
     
  • Use a do…while loop when you need the task to run at least once and then decide if it should continue based on a condition.
     
  • The choice between while and do…while depends on your specific needs in a program. If the initial run of the task is essential, do…while is your go-to. If the task needs to be conditional right from the start, then while might be more suitable.
     

To illustrate the difference between while and do…while loops in C, let's look at two examples. Both examples will aim to print numbers from 1 to 5, but under different conditions.

Example of while Loop

In a while loop, the condition is checked before executing the loop's body. If the condition is false from the beginning, the loop body will not execute at all.

  • C

C

#include <stdio.h>

int main() {

   int counter = 1;


  while (counter <= 5) {

       printf("%d\n", counter);

       counter++;  // Increment counter

   }

  return 0;

}

Output

Output

 

In this example, the loop checks if counter is less than or equal to 5. Since it starts at 1, the condition is true, and the loop prints numbers 1 through 5.

Example of do…while Loop

In a do…while loop, the loop's body is executed once before the condition is checked. This ensures that the loop's body is always executed at least once.

  • C

C

#include <stdio.h>

int main() {

   int counter = 1;

   do {

       printf("%d\n", counter);

       counter++;  // Increment counter

   } while (counter <= 5);

return 0;

}

Output

Output

Similar to the while loop example, this do…while loop also prints numbers 1 through 5. However, the key difference is that the loop's body would have executed once even if the initial condition was false (e.g., if counter started with a value greater than 5).

Frequently Asked Questions

Can do…while loops run infinitely?

Yes, do…while loops can run without stopping if the condition always remains true, just like any other loop. To prevent this, make sure your loop's condition will eventually become false. For example, updating a counter within the loop can help the condition become false at some point.

When should I use a do…while loop instead of a while loop?

Use a do…while loop when you need to ensure the code inside the loop runs at least once before checking the condition. It's useful when the initial execution of the loop's body is necessary, regardless of the condition's state.

How do I exit a do…while loop early?

You can exit a do…while loop early using the break statement within the loop. If a certain condition is met and you want to stop the loop immediately, break will exit the loop, even if the loop's main condition hasn't become false yet.

Conclusion

Understanding the do…while loop in C programming is key for situations where you need a task to run at least once before checking a condition. This loop is straightforward: do something first, then check if you need to keep doing it based on a condition. It's especially handy when the initial run is essential, no matter what the condition might be later.

Remember, the main difference from a while loop is that the do…while loop guarantees at least one run of its body, making it unique. With the examples and explanations provided, you should have a good grasp of how to use this loop effectively in your C programs.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Topics covered
1.
Introduction
2.
What is do…while Loop in C?
3.
Syntax of do…while Loop in C
4.
How to Use do…while Loop in C
4.1.
Start with do
4.2.
Write your task
4.3.
Check your condition
4.4.
Repeat or end
5.
How does the do…while Loop work?
6.
C do…while Loop Flowchart
7.
Nested do…while Loop in C
8.
Example
8.1.
C
9.
Examples of do…while Loop in C
9.1.
C
10.
Difference between while and do…while Loop in C
10.1.
When They Check Conditions:
10.2.
Usage
11.
Example of while Loop
11.1.
C
12.
Example of do…while Loop
12.1.
C
13.
Frequently Asked Questions
13.1.
Can do…while loops run infinitely?
13.2.
When should I use a do…while loop instead of a while loop?
13.3.
How do I exit a do…while loop early?
14.
Conclusion