Difference between While and Do-While Loop

Difference between While and Do-While Loop

6 mins read12K Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Sep 16, 2024 11:56 IST

The most important difference between while and do-while loops is that While loops check the condition before executing the loop body, potentially skipping it entirely if the condition is initially false. Do-while loops execute the loop body once before checking the condition, guaranteeing at least one execution regardless of the condition. Keep scrolling to understand the difference between while and do-while loop in detail.

2022_10_Feature-Image-Templates-44.jpg

 

Must Check: Top Programming Online Courses and Certificates

Table of Content

Recommended online courses

Best-suited C / C++ courses for you

Learn C / C++ with these high-rated online courses

4.24 K
6 weeks
475
6 weeks
– / –
45 hours
4 K
80 hours
– / –
1 month
– / –
40 hours
– / –
2 months
– / –
1 year
4 K
80 hours

 

Difference Between While and Do-While

Let's understand the key difference between while and do-while:

  • Execution guarantee: Do-while guarantees at least one execution of the loop body, while a while loop may not execute at all.
  • Condition placement: While checks before executing, do-while checks after executing.
  • Use cases:
    • While is better when you might not want to execute the loop at all based on the initial condition.
    • Do-while is useful when you always want to execute the loop at least once.
  • Syntax: Do-while requires a semicolon after the condition, while doesn't.

Let's go through this tabular comparison between them to understand it better:

Aspect While Loop Do-While Loop
Condition Check Beginning End
Minimum Executions 0 1
Syntax (C-style) while (condition) { ... } do { ... } while (condition);
Variable Initialization Variables are initialised before the execution of the loop.  Variables may initialise before or within the loop.
Exit Control Pre-test Post-test
Execution Guarantee No guarantee At least once
Semicolon Not required after } Required after condition
Initialization Before loop Can be within the loop body
Use Case When you need to check the condition before any execution When you want to ensure at least one execution
Example Scenario Checking if a file exists before processing Getting user input at least once

What is a While Loop?

Definition: While Loop is an entry-controlled loop that evaluates the condition before executing the body of the Loop, the body of the Loop will be executed only if the condition is True.

  • Once the body of the Loop gets executed, control again goes back to the beginning and then checks the condition.

Must Check: Top Java Online Courses and Certifications

Read Also: Loops in Java

Syntax

while (boolean condition)
{
     loop statements…
}

Working of While Loop

  • Initialization of Control Variable
  • Condition Check

Must Check: Top C++ Online Courses and Certifications

Read Also: For Loop in C++

Example

Using while Loop, print the first ten positive integers.

Code in C Programming Language


 
#include <stdio.h>
int main() {
int number = 1; // initializing the variable with value 1
while (number <= 10) { // while loop with condition
printf("%d\n", number);
number++; // incrementing operation
}
return 0;
}
Copy code

Output

1
2
3
4
5
6
7
8
9
10
 

What is a Do-While Loop?

Definition: A do-while Loop is an exit-controlled loop that evaluates the condition after the execution of the body.

  • The body of the Loop is always executed (at least once)
  • Once the body is executed, then it checks the condition:

Syntax

do
{
     statements….
}
while (condition);

Check out the best-rated job-centric courses after the 12th. Explore how online degree programs can prepare you for the job market

Working of Do-While Loop

  • Initialization of control variable
  • Loop Body gets executed first; then, the condition is evaluated

Example

Print the table of 5 in C Programming Language


 
#include <stdio.h> // Include the standard I/O library header
int main() {
int num = 1; // Initializing the variable with value 1
do {
printf("%d\n", 5 * num);
num++; // Incrementing operation
} while (num <= 10);
return 0;
}
Copy code

Output

5
10
15
20
25
30
35
40
45
50

Key Differences and Similarities between While and Do-While Loops:

  • While Loop is an “Entry Controlled Loop,” whereas Do-While Loop is an “Exit Controlled Loop.”
  • Do-while Loop uses a semicolon in the syntax, whereas While Loop does not use a semicolon.
  • While Loop evaluates the condition first and then executes the statement, whereas Do-While first executes the statements and then evaluates the condition
  • If the condition in a while loop is false, then not a single statement inside the Loop will be executed, whereas in a do-while Loop, if the condition is false, then the body of the Loop is executed at least once.
  • In the While loop, the condition statement is at the beginning, whereas the Do-While loop condition statement is at the end of the Loop.

Must Check: Top C Online Course and Certifications

Conclusion

The body of a while loop is executed after the given condition is evaluated, whereas in a do-while loop, the loop body is executed, and then the given condition is checked. In this article, we have briefly discussed the difference between a while and a do-while loop with examples.

Hope you will like the article.

Keep Learning!!

Keep Sharing!!

Related Reads

C programming Keywords: A list and Explanation of Usage
C programming Keywords: A list and Explanation of Usage
Keywords in C refer to a set of reserved words with predefined meanings that are used to write programs in the C programming language. These keywords cannot be used as...read more
Introduction to For Loop in C
Introduction to For Loop in C
A loop is one of the most fundamental logical structures in computer programming. Defining loops in code allows computers to repeat specific tasks. Defining the loop in a computer program...read more
Malloc in C Programming: How to Allocate Memory Dynamically 
Malloc in C Programming: How to Allocate Memory Dynamically 
This article covers the concept of dynamic memory allocation in C programming, which allows allocating memory at runtime according to the program’s needs using functions like malloc(), calloc(), realloc(), and...read more
Function Prototype in C
Function Prototype in C
This article defines the scope of function prototype Importance, examples of Function Prototype and Difference between Function Prototype and Function Definition in C This article defines the scope of function prototype...read more
Learn to Implement strstr() Function in C
Learn to Implement strstr() Function in C
Discover how to use the Strstr function in the C programming language, including its syntax, parameters, and practical applications. Explore examples and tips to effectively implement Strstr in your code...read more
Concatenate Strings with strcat() Function in C
Concatenate Strings with strcat() Function in C
This article offers a comprehensive explanation of the syntax and implementation of the strcat() function, in addition to providing several examples to aid in understanding its operation. By the end...read more

 

FAQs

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

Use a while loop when you want to check the condition before executing the loop body, potentially skipping it entirely if the condition is initially false.

What's the main advantage of a do-while loop over a while loop?

The main advantage of a do-while loop is that it guarantees at least one execution of the loop body, which is useful when you always need to perform an action before checking a condition.

In terms of performance, is there a significant difference between while and do-while loops?

Generally, there's no significant performance difference. The choice between them should be based on the logic required by your program rather than performance considerations.

Can a do-while loop execute zero times?

No, a do-while loop always executes at least once, even if the condition is false from the start.

In what scenario would you prefer to use a do-while loop over a while loop?

You would prefer to use a do-while loop over a while loop in scenarios where you want to ensure that a block of code executes at least once before checking a condition. Here are some specific situations:

  1. User input validation: When you need to get input from a user and validate it, you often want to prompt the user at least once, even if their first input might be correct.
  1. Menu-driven programs: When displaying a menu and processing user choices, you typically want to show the menu at least once before checking if the user wants to exit.
  2. Processing data with unknown initial state: When you need to process data but don't know its initial state, a do-while loop ensures you perform the processing at least once.
  3. Game loops: In simple games, you might want to ensure the game runs at least one cycle before checking exit conditions.
  4. Initialization with complex logic: If the loop's condition depends on operations that need to be performed first, a do-while loop can be more appropriate.

The key consideration is whether your logic requires at least one execution of the loop body before evaluating whether to continue. If so, a do-while loop is often more suitable and can lead to cleaner, more intuitive code.

Describe a real-world programming scenario where a do-while loop would be more appropriate than a while loop.

A real-world programming scenario where a do-while loop would be more appropriate than a while loop is implementing a simple ATM transaction system. Here's why:

  1. Scenario: ATM Transaction Process

In an ATM system, once a user has logged in, you want to present them with options to perform transactions (withdraw, deposit, check balance, etc.) and allow them to continue performing transactions until they choose to exit.

  1. Why do-while is more appropriate:
    • Initial display: You always want to show the transaction menu at least once after login.
    • User interaction: The user should be able to perform at least one transaction before deciding to continue or exit.
    • Exit condition: The condition to exit (user choosing to quit) is checked after each transaction, not before.

In this scenario, a do-while loop ensures that:

  1. The transaction menu is always displayed at least once.
  2. The user can perform at least one transaction.
  3. The option to exit is presented after each transaction, not before any transactions occur.

Using a while loop here would be less intuitive, as it would require either duplicating the menu display code or using a flag variable to force the first iteration, making the code more complex and less readable.

This ATM example demonstrates a common pattern in interactive programs where you want to ensure at least one cycle of operation before checking if the user wants to continue, making it a perfect use case for a do-while loop.

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio