Do While Loop in C

Do-while-loop-feature-image.jpg

The do-while loop in C is a fundamental programming concept that every C programmer must understand. Unlike other loops, the do-while loop guarantees that the code block is executed at least once, making it unique and useful in specific programming scenarios. This article will discuss the do-while loop in the C programming language. It will explain the syntax and help you understand the concept better with the help of real-world examples.

Table of Contents:

What is a do-while Loop in C?

A do-while loop in C is a loop structure that executes a block of code at least once before checking the loop condition, which is the primary difference that sets it apart from the while loop, which tests the condition before executing the code block. In C programming, loops are used when you want to code a repetitive task. Using loops makes your code efficient, easy to understand, maintain, and may even reduce the complexity of your code. The do-while loop is especially useful when you need to ensure that a block of code runs at least once, before the condition gets checked. Now, let us look at the syntax of the do-while loop in detail. 

Syntax of Do-while Loop in C

The syntax of the do-while loop in C is as follows. 

do {
    // Code block to be executed
    // Statements
} while (condition);
  • The do keyword comes first, indicating to the compiler that this code should be executed first. 
  • Then comes the while keyword followed by the condition it needs to check. 
  • After the do code block has been executed, this do-while loop behaves normally like a while loop, checking the conditions and then executing based on the condition.

Let us now look at an example applying the basic syntax we just learned. 

Master C & DSA for Free!
Enroll Now for Free and jumpstart your programming journey!
quiz-icon

Basic Syntax Example:

C

Output:

Basic Syntax Example:

Explanation: This is a very simple implementation of the do-while loop. Here we declared a variable i and used the condition i <= 5 so that the loop terminates when the variable i is equal to 5. 

How Do-While Loop Works 

Even though we have discussed the flow of the do-while loop briefly, let us now understand the flow of execution with the help of proper steps and a flowchart.

  1. Initialization: First, the variables that will be used in the loop for the condition increment or decrement are initialized before the loop begins. It is important so that the loop doesn’t execute infinitely and throw any errors. 
  2. Execute Code Block: Next comes the execution of the do block of the code. The statements inside the do block are encountered first and hence are executed. 
  3. Update: If the code made any increment or decrement operations, the concerned variables are modified and updated. 
  4. Condition Check: Next, we check the condition inside the while loop after code execution. After evaluation, the condition results in either true or false. The result of your condition must be of the Boolean type. Even if it is an integer value, it is typecast to a boolean value. Any non-zero integer is considered True, and zero is considered False. 
  5. Decision: If the condition is true, the loop repeats, and if it is false, the loop terminates then and there. 

Flow Diagram Explanation:

How Do-While Loop Works

Example of Do-While Loop in C

Now that you are familiar with the basics, let’s make your understanding stronger with the help of some practical examples of a do-while loop in C with detailed explanations:

1. Print 1 to 10

C

Output:

Example 1 do while loop in C

Explanation: 

  • This code uses a do-while loop to count and print numbers from 1 to 10. We will initialize a num variable that will be incremented throughout the code. 
  • Inside the “do” part of the loop, it prints the current number (the current value of num) and then increments num by 1.
  • After each print, the condition in the while part of the code checks if num is still 10 or less. If the condition is true, the loop repeats. Otherwise, it terminates, and the program says “Loop terminated.”

2. Menu-Driven Program

This next example will illustrate how the do-while loop is used in the real world with the help of a menu-driven program. You can use a do-while loop so that when the program starts, the do block of code is used to load the menu (which must run all the time) and then a while loop with a switch case statement inside, to let the user make their choice. The condition is that if the user chooses option 3 (which is to exit the program), it keeps running. 

Code:

C

Output:

Menu-Driven Program

Explanation:

  • The program first displays the menu, which is inside the do block of the code; therefore, it will run regardless of whether the condition is true or false.
  • Next, option 1 is chosen, so “You selected Addition” prints.
  • Then, the do-while loop checks if your choice is 3. Since it’s 1, the loop runs again, displaying the menu once more.
  • Then, the user enters 3. “Exiting program…” prints, and this time the loop condition (choice != 3) becomes false, so the program ends. 

Get 100% Hike!

Master Most in Demand Skills Now!

3. Input Validation

The do-while loop is also used in Input validation. Here, the do block is used to prompt the user to enter their password, and then the while loop validates the password against your password saved in the database.

Code:

C

Output:

Example 3 do while loop in C

Explanation: 

  • The program first asks for a password. When we typed sbv bdvk (which are not numbers), the program identified it as “Invalid input!” and prompted us again.
  • This repeats when ujwebd is entered, which again fails the condition password != correct_password, so the program keeps asking you for a password that contains numbers and matches the correct password.
  • Next, 4573 is entered. It is a number, but it doesn’t match the secret correct_password (which is 1234). So, the program says “Incorrect password! Try again.
  • The do-while loop keeps running because the password entered is still not the correct one.
  • Finally, the correct password was entered (1234), which the program recognizes as the correct password, and the loop stops. Finally, ‘Access granted!’ is displayed, and the loop terminates

Difference Between while and do-while Loop in C

By now, it must be very clear how the while loop is different from the do-while loop. Given below is a well-organized table that gives the difference between the while loop and do-while loop structure to help you remember it better. 

Aspect While Loop Do While Loop
Testing Type Pre-tested loop Post-tested loop
Condition Check Checked before execution Checked after execution
Minimum Execution May not execute at all Executes at least once
Syntax while(condition) { } do { } while(condition);
Semicolon Not required after condition Required after condition

When to Use While Loop vs Do While Loop in C

In this section, we will discuss the proper conditions for when to use a while loop and when to use a do-while loop.

1. Use a while loop when:

  • You need to check a condition before the loop runs as a validation or authentication measure. 
  • The code inside the loop might not need to happen even once if the condition isn’t true from the start.
  • It is great for checking things like user input, especially if their first answer could already be correct, so you don’t ask them again for no reason.

2. Use a do-while loop when:

  • You need the code inside the loop to run at least once, no matter what the condition is at first.
  • They are good for showing a menu to a user and getting their first choice before deciding if they want to do something else (like “Exit“).
  • It makes sure the user is asked for input at least once, even if the condition to ask again would initially be false.

Common Mistakes When Using Do-While Loop

As a beginner, you are bound to make mistakes. Below is a list of such mistakes and how to avoid these common errors, which will improve your programming:

1. Forgetting the Semicolon

  • After the while (condition) part of a do-while loop, you must always put a semicolon (;). Forgetting this semicolon is a common typo and will cause a syntax error, meaning the compiler doesn’t understand your code.

2. Infinite Loop Creation

  • A loop needs something to stop it from running and running and resulting in an infinite loop. If the variable used in your loop condition (or the variable used in the loop condition) never changes in a way that makes the condition false, the loop will run endlessly. 
  • For example, if you are counting up but forget to add to your counter variable, the condition will always be true, trapping your program in an “infinite loop.”

3. Incorrect Condition Logic

  • Even if your loop variable changes, the condition you set might not be logically correct for when you want the loop to stop.
  • For example, if you want to count up to 5 but your condition says “keep going as long as the number is greater than or equal to 5,” the loop might run only once (if starting at 1) or never stop if it starts above 5. The condition must correctly reflect when the loop should continue and when it should end.

4. Variable Scope Issues

  • When you create a variable inside the do part of the loop, that variable only exists within that specific do block. Each iteration creates a new instance of the variable. The while (condition) part, which is outside the do block, cannot “see” or use variables that were created only inside the do block. To use a variable in your loop’s condition or to have its value carry over from one loop run to the next, you must create that variable before the do-while loop begins.

Conclusion

The do-while loop in C is a programming concept that ensures the code block executes at least once, as its condition is evaluated after the initial run. It is important to remember to include a semicolon after the while condition. This loop structure is well-suited for applications such as menu systems or input validation, where an initial action or input attempt is always required. Proficient use of the do-while loop, alongside avoiding common errors like missing semicolons or unintentional infinite loops, will significantly enhance your C programming skills.

Do While Loop in C – FAQs

Q1. What is a do-while loop in C?

You can use a do-while loop to run code at least once, since the condition is checked after the loop body.

Q2. When should you use a do-while loop in C?

You should use it when the loop body must execute at least once, such as in menu-driven programs or input validation.

Q3. What is the syntax of a do-while loop in C?

The syntax of the do-while loop is as follows: do { // code} while (condition); Don’t forget the semicolon after the while statement.

Q4. Can you nest do-while loops in C?

Yes, you can nest do-while loops inside each other, just like for or while loops, depending on your logic.

Q5. What is the difference between while and do-while loops in C?

You use while to check the condition before running code; do-while checks it after, ensuring the loop runs at least once.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner