Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

The Difference Between While and Do While Loop in C

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

Loops are a very important part of any programming language. They are the fundamentals of programming as they help execute a block of code for a given time or repeatedly until a specified condition is met. While the C language has 3 types of loops, including for, while, and do-while, we will learn the differences between while and do-while loops in this article.

 

While the naming might seem similar, they have different workings, which will be discussed in this article, too. In this blog, we will dive into the functionalities of while and do-while loops to see their key differences and provide practical code examples for a better understanding. Let’s learn more in detail about while and do-while loops in the C language.

What is the While Loop in C?

A while loop is a control flow statement in which the loop body is executed till a certain condition is met. While loop is also known as an entry–controlled loop or pre-condition loop, where a condition is checked before the code inside is executed. Once a condition is checked, the iteration continues till the condition remains true. Let’s see the while loop syntax first.

 

Syntax

Below is the syntax used for defining a while loop in C language:

while (condition) { // body content to be executed }

How Does a While Loop Work?

A while loop is a controlled flow statement in which the given condition is checked before executing the code. See the complete step-by-step working of a while loop in C language below:

 

  1. First, the condition is evaluated.
  2. Then, If the condition == true, the code inside the loop is executed.
  3. After executing the code, the condition is then re-evaluated.
  4. Finally, the process continues until the condition == false.

 

while loop

Note that a while loop can also be nested, which means there can be more than 2 while loops executed one inside the other.

 

Single While Loop:

There is no single while loop; it’s just a way to describe the usage of a while loop. The working of a single while loop is very simple, wherein it first evaluates the condition. If true, the given code inside the loop is executed, and if not, then it returns. See the syntax and example of a single while loop below.

 

Syntax:

 

Below is the syntax used for defining a while loop in C language:

while (boolean condition) { // body content to be executed }

Code Example: The below example demonstrates a single while loop in C.

#include <stdio.h>   int main() { int name_count = 15;   while (name_count > 5) { // boolean condition printf("Welcome to HeroViredn"); // Print the message until name_count is greater than 5 name_count--; } }

Explanation:

 

  • In this example, we are printing the message “Welcome to HeroVired”.
  • Here, a while loop is used, and the condition name_count > 5 is evaluated first.
  • Inside the while loop, the program executes to print a message “Welcome to HeroVired” and then decrements the value of name_count by 1.
  • The loop continues to execute as long as the condition name_count > 5 remains true.
  • When name_count <= 5, the loop terminates.

 

Output:

Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired

Nested While Loop:

 

A while loop can be nested inside one another and executed. Here, there are two things: an outer loop that controls the overall repetitions and an inner loop that executes a specific set of statements within each iteration of the outer loop. See the syntax and example of a nested while loop below.

 

Syntax:

Below is the syntax used for defining a nested while loop in C language:

while (boolean out_condition) { // Outer loop body content while (boolean in_condition) { // Inner loop body content … } }

Code Example: The below example demonstrates the nested while loop.

#include <stdio.h> int main() { int row_no = 10; // Initialize the rows int cols_no = 5; // Initialize the cols while (row_no > 2) { // Outer loop as row no int col_no = 2; while (col_no <= cols_no) { // Inner loop as column no printf("HeroVired "); col_no++; } printf("n"); // Print to next line after each row row_no--; } }

Explanation:

 

  • In this example, we are printing a message “HeroVired” in an 8 * 4 size after initialising two variables with value row_no = 10 and cols_no = 5, representing the number of rows and columns, respectively.
  • Here, the outer while loop iterates as long as row_no > 2. Inside this loop, the program enters another nested do-while loop.
  • Inside the outer loop, an integer variable col_no = 2 and the inner while loop iterates as long as col_no <= cols_no
  • Inside this loop, the program prints the message, and after each iteration of the inner loop, col_no is incremented by 1.
  • Once the inner loop completes its iterations for a row, the program prints a message, and the outer loop decrements row_no by 1 using row_no–.
  • The outer loop continues to execute until row_no <= 2.

 

Output:

HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired

Also Read: Difference Between Java and Python

What is the Do-while Loop in C?

A do-while loop is a control flow statement in which the loop body is executed till a certain condition is met. A do-while loop is also known as an exit–controlled loop or post-condition loop, where a condition is checked after the code inside is executed once. The do-while loop guarantees the loop body will be executed at least once before checking the condition regardless of whether the condition is true or false. Let’s see the do-while loop syntax.

 

Syntax

Below is the syntax used for defining a do-while loop in C language: <strong> </strong> do { // body content to be executed at least once … } while(condition)
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

How Does a Do-while Loop Work?

A do-while loop is a controlled flow statement in which the code is executed at least once before checking the condition. See the complete step-by-step working of a do-while loop in C language below:

 

  1. First, the code is executed once.
  2. Then, the condition is checked/evaluated.
  3. Now, if the condition == true, the loop body is again executed.
  4. Finally, the process continues until the condition == false.

Do while

Note that a do-while loop can also be nested, which means there can be more than 2 do-while loops executed one inside the other.

 

Single do-while Loop:

 

In a single do-while loop, the loop body is executed at least once, and only then is the condition or test expression tested/evaluated. In this do-while loop, the working is very simple: first, the body is executed, and then the condition is checked. If the condition becomes true again, the body is again executed, and if false, then it returns. See the syntax and example of a single do-while loop below.

 

Syntax:

Below is the syntax used for defining a do-while loop in C language:

do { // body content to be executed at least once } while (boolean condition)

Code Example: The below example demonstrates the single do-while loop.

#include <stdio.h> int main() { int name_count = 10; do { printf("Welcome to HeroViredn"); // Print the message until name is greater than 4 name_count--; } while (name_count > 4); // boolean condition }

Explanation:

 

In this example, we are printing the message “Welcome to HeroVired” using a do-while loop that ensures the message is printed at least once. Here, the name_count starts at 10 and is decremented within the loop till the name_count becomes 4. The loop continues as long as name_count is greater than 4, resulting in six iterations and six printed messages.

Output:

Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired Welcome to HeroVired

Nested do-while Loop:

 

In a nested do-while loop, the working is similar to that of a nested while loop. The outer do-while loop controls the overall iterations, while the inner loop executes at least once before checking the test expression or condition. See the syntax and example of a nested do-while loop below.

 

Syntax:

 

Below is the syntax used for defining a nested do-while loop in C language:

do { // Outer loop body content do { // Inner loop body content } while (boolean inner_testExpression); } while (boolean outer_testExpression);

Code Example: The below example demonstrates the nested do-while loop.

#include <stdio.h>   int main() { int r_no = 1;   // Outer do while loop do { int c_no = 1;   // Inner do while loop do { printf("HeroVired"); // Printing the message using inner loop c_no++;   } while (c_no <= 3);   printf("n"); r_no++;   } while(r_no <= 6);   return 0; }

Explanation:


In this example, we have created a 6 * 3 rectangle using a nested do-while loop. Here, the two variables r_no and c_no are declared as row and column, respectively. The outer loop controls the number of rows printed, while the inner loop controls how many times the “HeroVired” message is printed in each row.

 

Output:

HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired HeroVired

Difference Between While and Do-while Loops in C

Some of the key differences between the while and do-while loops are given below:

 

Parameters While Loop Do-while Loop
Entry condition In a while loop, the condition is pre-evaluated before execution. In a do-while loop, the body is executed once before a condition is evaluated.
Use Case It is generally preferred when you need to check or evaluate the condition first. It is generally preferred when you need to run/execute the code first at least once before evaluating the condition.
Condition Evaluation The condition in a while loop is evaluated at each iteration. The condition in a do-while loop is evaluated at the end of the iteration.
Loop body execution In this, the body content may not execute even once if the condition is false initially. In this, the body content is guaranteed to execute even once if the condition is false initially.
Loop termination It terminates the loop when the condition is false. It terminates when the condition is false after the body has been executed.
Initialization In a while loop, any counter variable is initialised before the loop. Here, the initialization can be done before or after.
Nested loops Here, the nested loops can be created. Here also the nested loops can be created.
Memory The memory usage is the same in both. The memory usage is the same in both.
Complexity The usage of while is simpler. The usage of a do-while loop is generally complex as compared to a while loop.
Flexibility It is less flexible due to the body execution. It is more flexible as the body is executed at least once, even before the condition is evaluated.
Error Handling Using a while loop is less prone to an infinite loop. It is more prone to infinite loops if not carefully handled.
Loop Control Flow It is an entry-controlled loop. It is an exit-controlled loop.
Syntax while (condition) {
// body content to be executed
};
do {
// body content to be executed at least once

} while(condition)

Conclusion

In this blog, we learned the differences between the while and do-while loops in C. Understanding the differences between both these loops can help you in determining where to use them and how to use them as they provide you with a complete understanding of the condition or test expression check and execution.

 

We saw how the while loop evaluates the condition before the loop body, making it suitable for scenarios where the loop might not execute at all if the condition is false initially. We also saw the working of a do-while loop on how it checks the condition after the loop body, ensuring that the loop executes at least once.

FAQs
Infinite loop is a big issue in loops in every programming language. Both while and do-while loops can go in a state where the condition never becomes false, and the loop is running infinitely. To avoid an infinite loop, use or declare any variable or a function to update the variable used in the condition so that it can eventually become false and terminate the loop.
Generally the while loop is considered easier as compared to the do-while loop due to its straightforward nature.
Yes, both while and do-while loops can be nested.
You should use a while loop when you want to execute the loop body only if the condition is true initially. It's preferred when you want to check the condition first before executing the loop body.
Yes, you can definitely use the break and continue statements within both while and do-while loops in C, as they provide great control over the flow of execution within the loop.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

19 October, 12:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved