Table of content:
Do-While Loop In C Explained With Detailed Code Examples
There are several constructs in C programming that help us control the flow of a C program. We refer to such constructs as control statements and loops form an important part of these tools. In this article, we will discuss a specific type of loop, i.e., the do-while loop in C, in detail.
The do-while loop is a versatile and powerful tool that comes in handy in various programming scenarios. We will explore the syntax, behavior, use cases, advantages, and examples of the do-while loop in C programming.
Loops In C
Before we move to discuss the do-while loop, it is important to iterate on what loops are and their different types. Loops in C programming language are the control flow statements that are used to repeat some part of the code until the given condition or base condition is satisfied. In other words, they facilitate the repetitive execution of a block of code based on some pre-specified conditions being met. There are three major types of Loops:
- For Loop
- While Loop
- Do-While Loop
What Is Do-While Loop In C?
The do-while loop is a combination of two words, do, and while, which means firstly, it will perform or carry out an action (which is to execute a piece of code), and then it will work as a while loop based on its base condition.
Since we can say that a do-while loop in C is a looping statement that executes a piece of code at least once. It is a type of post-tested loop which executed at least one time.
Syntax Of Do-while Loop In C:
do {
// Piece of code
} while (condition);
Here,
- The do keyword marks the beginning of the do-while loop in C.
- The piece of code inside the do block quotes or curly brackets makes the body of the loop. It contains the code statements that are executed at least once.
- The condition following the while keyword specifies the looping/ boolean condition, which will return true or false. The loop will continue to execute till the condition remains true.
How Does The Do-while Loop In C Work?
The flow diagram given above showcases how the flow of control moves across the do-while loop in C. Below is a step-by-step of the working mechanism for this loop, supported by the diagram above.
- As the program flow enters a do-while loop, the code inside the loop body is executed first.
- After that, the flow moves to the condition mentioned after the while keyword. The program evaluates this loop test condition.
- If the condition evaluates to false, the loop terminates, and the flow of the program moves out of the do-while loop.
- If the condition is true, then the execution flow moves back to the start of the loop.
- It once again executes the loop body and then checks the loop's conditional expression. and executes the body of the loop once again. This continues until the loop condition becomes false.
- After the termination of the loop, the program continues the rest of the code.
Example Of Do-while Loop In C
We now know what a do-while loop is and the working mechanism behind this construct. In this section we will look at a few examples of this loop to gain a better understanding of the same.
Example 1: Basic Execution Of Do-while Loop In C (5 iterations)
Output:
#BeUnstoppable
#BeUnstoppable
#BeUnstoppable
#BeUnstoppable
#BeUnstoppable
Explanation:
We begin the simple C program by including the <stdio.h> library and then define the main() function.
- Inside main(), we declare a variable i of integer data type and initialize it with the value of 0.
- Then, as mentioned in the code comments, we initiate a do-while loop to print a string literal a certain number of times iteratively.
- Inside the loop body, we have a printf() function, which displays the string value- #BeUnstoppable to the console.
- The newline escape sequence ensures that the output of every iteration is printed in the next line.
- After the execution of printf(), the value of the control variable i is incremented by 1.
- The program then moves to check the while condition, i.e., i<5.
- If the condition is true, the code inside the loop is executed repeatedly until the condition becomes false.
- When the condition in while() is false, the loop gets terminated, and control is passed outside of the loop.
- After the ending of the loop, the program returns 0, indicating an error-free execution.
Time Complexity: O(1)- Since the loop is running 5 times in total and the loop count is constant, i.e., 5, the time complexity will be O(1).
Example 2: Print Natural Numbers With A Do-While Loop In C
Output:
Enter any number: 4
Natural numbers from 1 to 4 are:
1
2
3
4
Explanation:
In this sample C program, we begin by including the input/ output header file.
- Inside the main() function, we declare two integer variables i and n. Of these, we initialize i to the value of 1 using the simple assignment operator.
- We then use the printf() function to prompt the user to input a value, which we then store to variable n, using the scanf() function and a formatted string.
- In the formatted string, we have a %d format specifier to indicate that we are reading an integer value and also the reference/ address-of operator to indicate the address of n.
- Then, we initiate a do-while loop to count and print natural numbers up to n. For this-
- The do-block contains a printf() statement, which we use to print the current value of loop control variable i.
- After that, we use the post-increment operator to increase the value of i by 1.
- Then, the control moves to the while condition. So, the program checks if the value of i is less than or equal to n.
- If the condition is true, the loop is executed again. If the condition is false, the flow moves outside of the loop.
- In this example, the input we are taking is 4. So, the loop executes 4 times before it terminates.
- After that, the program returns 0, indicating zero errors and a successful execution.
Time Complexity: O(n)- Since the loop is running n times, the time complexity will be O(n).
Also read- Compilation In C | A Step-By-Step Explanation & More (+Examples)
Nested Do-While Loop In C
A nested do-while loop in C is a loop in which one do-while loop is placed inside another do-while loop. This allows you to execute the set of statements in a hierarchical manner.
Each time the outer do-while loop executes, the inner do-while loop will execute till its conditional statement gets false, and then it returns the control to the outer loop.
Syntax of nested do-while loop in C:
do {
// Outer loop body
do {
// Inner loop body
} while (inner_condition);
// Updation condition/ Code after the inner loop
} while (outer_condition);
Here,
- We have one do-while loop nested inside the other, with the do keywords marking the beginning of each.
- The curly braces contain the code statements to be executed for the respective do-blocks.
- The inner_condition and the outer_condition refer to the test condition for the inner and the outer loops, respectively.
Now, let's take a look at the working mechanism of the nested do-while loop in C before moving to an example that showcases its implementation. Here is how the nested do-while loop works-
- The program enters the nested do-while loop, and the code inside the outer loop body is executed.
- The flow then moves to the inner do-while loop, and the corresponding code is executed.
- After that, the program checks the inner condition. If this is true, the inner loop is executed again.
- If and when the inner condition returns False, the flow moves back to the outer loop.
- If there is an updating condition given for the outer loop (this will be after the inner loop closes), then the value of the control variable is updated. The code body of the outer loop is executed again.
- The program again moves to the inner loop, and steps 2 to 4 are repeated.
- While the outer loop runs until the base condition of this loop becomes false.
- When the base condition of the outer loop becomes false, it exits the loop.
Below is an example where we use the do-while loop to print the star pattern to the console.
Code Example:
Output:
Here is your pattern:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Explanation:
We begin the sample C code by including the <stdio.h> library.
- Inside the main() function, we declare two integer variables, i and j, of which we initialize i with the value of 1.
- We then use the printf() function to display a string/ message to the console and shift the cursor to the next line by using the newline escape sequence (\n).
- Then, we initiate a nested do-while loop. Here-
- In the outer loop, we initialize variable j with the value of 1., and move to the inner loop.
- The printf() statement in the inner loop displays an asterisk to the console, followed by a space.
- The value of j is increased by 1, and the program then moves to check the inner loop condition, i.e., j<=5. This means that the inner loop will continue printing asterisks in the line 5 times (i.e., till j becomes 5).
- After this, the control will move back to the outer loop where another printf() statement moves the cursor to the next line, and the value of i is incremented by 1.
- The program then checks the outer condition, i.e., i<=5. If the condition is true, the inner loop will be executed again.
- As a result, the inner loop will print the asterisk (*) to the console 5 times in a single line. And the outer loop will ensure that this happens for 5 lines (or 5 times). This is how we will get our square star pattern.
- The control moves out of the nested loop when the value of i is greater than 5, i.e., the outer loop condition returns false.
- Finally, the program will end with a return 0 statement.
Time Complexity: O(n^2)- For every value of i, the inner loop will run j times, so time complexity will be O(n^2).
Infinite Do-while Loop In C
An infinite loop, as the name suggests, is a loop that repeats its code blocks indefinitely. In other words, it is a loop where the base condition always returns the true value, thus leading the loop to run indefinitely.
Similarly, an infinite do-while loop is one where the condition is always true, and the execution continues indefinitely until someone terminates it externally/ manually. We can specify its base condition as 1 or True to create an infinite loop.
Syntax of Infinite Do-While Loop In C:
do {
// code to be executed
} while (condition);
Here, the syntax is the same as the one for a regular do-while loop in C. But the difference comes in the condition of the loop, as the condition for an infinite loop is always true. This could be done by not including an updating condition, such that the base condition is always fulfilled.
Code Example:
Output:
I am Unstoppable
I am Unstoppable
I am Unstoppable
I am Unstoppable
....
Explanation:
We begin this example code by:
- Including the header file and initializing the main() function which serves as the entry point of the program's execution.
- We initiate a do-while loop in main(), where the printf() function displays the string- I am Unstoppable to the console. The newline escape sequence shifts the cursor to the next line.
- The program then moves to check the looping condition, which is 1.
- This condition always remains true, and the loop keeps on printing the string message continuously.
- This happens indefinitely until someone terminates the program manually. After which, the program will return 0, indicating successful execution.
Advantages & Disadvantages of Using Do-While Loop In C
The do-while loop in C has its own advantages and disadvantages, and understanding them can help in choosing the appropriate loop construct for a given situation.
The following are the advantages of using a do-while loop in C:
- Always Executes at Least Once: The primary advantage of the do-while loop is that it guarantees the execution of the loop body at least once, regardless of the initial condition. This can be useful in situations where you need to perform an action before checking the loop condition.
- Cleaner Code for Certain Scenarios: In some cases, using a do-while loop can result in cleaner and more concise code, especially when there is a need to execute a block of code at least once.
- Simplifies Input Validation: The do-while loops are often used for input validation, where user input needs to be checked and validated at least once. This simplifies the code as the validation code is placed at the end of the loop.
Here are a few disadvantages of using a do-while loop in C:
- Potential for Infinite Loops: If the loop condition is not properly updated within the loop body, there is a risk of creating an infinite loop. This can lead to the program hanging or crashing.
- Limited Use for Certain Control Structures: The do-while loop's always-executes-once behavior may not be suitable for all scenarios. In situations where precise control over loop entry is required, the while loop might be preferred.
- Less Commonly Used: While the do-while loop is powerful, it is less commonly used than the while loop in practice. Developers often default to the while loop for its simplicity and ease of understanding.
Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions
The While Loop In C
A while loop is a pre-tested loop that executes a block of code repeatedly until the base or given condition remains true. The meaning of a pre-tested loop is that the given condition is checked first, and then the body of the loop is executed.
This is in contrast to the do-while loop in C, but both loops can be used in place of the other depending on the requirement of the program. In this section, we will discuss the while loop in brief and then provide a comparison between the two.
Syntax:
while(condition) {
// Code Body
}
Below is an example of a C program where we use the while loop to print n natural numbers. This example is similar to the one we used for the do-while loop above to make comparison easier. Let's get started!
Code Example:
Output:
Enter any number: 4
Natural numbers from 1 to 4:
1
2
3
4
Explanation:
In the code example above-
- We declare two variables, i and j, inside the main() function and initialize i to the value of 1.
- Then, we use the printf() function to prompt the user to input a value, which we then store to variable n using the scanf() function.
- Next, we create a while loop to print the value of natural numbers till n. Here-
- The initial loop condition checks if the value of the control variable i is less than n.
- If the condition is true, then the printf() statement is executed to display that value to the console.
- After that, the increment operator updates the value of i, and the condition is checked again.
- The loop body is executed till the condition returns true. And we exit the loop when the condition becomes false.
- In this example, the input value is 5, so the loop executes 5 times, printing the number from 1 to 5.
- After that, the program returns 0, indicating successful implementation.
Time Complexity: O(n)- Since the loop is running n times, the time complexity will be O(n).
To know more about while loop, read- While Loop In C, Infinite, Nested, And More! (+Code Examples)
While Vs. Do-while Loop In C
The while and do-while loops in C are both used for the repetitive execution of a block of code as long as a certain condition is true. However, they differ in when they check the loop condition, which can affect how they behave in certain situations.
Here are the main differences between the while and do-while loops in C:
While Loop |
Do-While Loop |
The given condition is evaluated first, and then the loop body is executed. |
The given loop body is executed first, and then the given condition is checked. |
It is a pre-tested or entry-controlled loop. |
It is a post-tested or exit-controlled loop. |
It allows the initialization of the counter variable before entering the loop. |
It allows the initialization of the counter variable before and after entering the loop. |
No semicolon is used as a part of the syntax, i.e., while(condition) |
Semicolon is used as a part of the syntax, i.e., while(condition); |
Syntax: while(condition){ |
Syntax: do{ |
Conclusion
The do-while loop in C is a valuable tool, especially when there is a need to guarantee the execution of a block of code at least once. Its distinctive behavior sets it apart from other loop constructs, and understanding its strengths and weaknesses is essential for effective and error-free programming. By incorporating the do-while loop into your programming arsenal, you can enhance code readability, handle user input more gracefully, and efficiently address various programming challenges.
Frequently Asked Questions
Q. Is a do-while loop a pretest loop? What is the syntax of the do-while loop in C?
No, a do-while loop is a post-tested loop, not a pre-test loop. A post-tested loop is one where the code block of the loop body is executed first, and then the given condition is checked. In contrast, a pretested loop is a loop in which the given condition is checked first before executing the loop body. Examples of pretested loops include the for loop and the while loop.
The syntax of the do-while loop in C is as follows:
do{
//Piece of code
}while(condition);
Here, the do keyword marks the beginning of the loop, the piece of code in the curly brackets makes the body of the loop, and the condition is the test expression that determines if the loop will continue execution or terminate.
Q. What are the entry-controlled or pre-tested loops?
An entry-controlled loop is a loop that tests the base or given condition of the loop before executing the code blocks of the body. An example of an entry-controlled loop is a while loop.
Code Example:
Output:
Enter a number greater than zero: 3
Current Number 3
Current Number 2
Current Number 1
The loop has ended.
Explanation:
- In this example, we prompt the user to input a value greater than zero using the printf() function.
- The program then enters a while loop where we check the condition n>0. If this condition is true, we execute the code inside the body, i.e., print the value of the number.
- The value of the control variable n is then decreased by 1, and the loop continues execution till the base condition becomes false, i.e., until the value of n becomes zero.
Q. What are the exit-controlled or post-tested loops?
An exit-controlled loop is a loop that tests the loop condition after exiting the loop body and executing the code. In other words, the condition of the loop is checked after executing the code blocks of the body at least once.
An example of an exit-controlled or post-tested loop is the do-while loop. The syntax of the do-while loop is:
do {
// Piece of code
} while (condition);
Here,
- The do and while keywords mark the beginning of the loop and the definition of the loop condition, respectively.
- The code inside the curly brackets makes up the body of the code, which is implemented if the condition returns true. In a do-while loop, this will be executed at least once.
- The condition refers to the loop test expression, which determines if the loop body will continue to be executed. It is a boolean expression which either returns true or false.
Q. Can I nest do-while loops within each other or combine them with other loop types?
Yes, you can nest different or the same types of loops inside the do-while loop. Nesting loops or combining different types of loops allows us to check a wider range of conditions and meet a variety of programming requirements. For example, they are useful when working with multidimensional data or intricate problems that require us to carry out multiple iterations. Below is an example that shows the implementation of this concept for a deeper understanding.
Code Example:
Output:
Do-while loop iteration: 1
While loop iteration: 1
While loop iteration: 2
While loop iteration: 3
Do-while loop iteration: 2
While loop iteration: 1
While loop iteration: 2
While loop iteration: 3
Explanation:
- In this example, we have used a while loop nested inside a do-while loop.
- We begin by initializing the doWhileLoop variable to the value of 1 inside the main() function.
- Then, we begin the do-while loop and use a printf() statement to display the iteration number for the do-while loop with a message.
- Next, we initialize the value of the whileLoop variable to 1 and enter the nested while loop.
- Inside this, we first check the base while condition, i.e., whileLoop<=3. If this condition is true, the while loop body is executed, i.e., the printf() displays the iteration number of the while loop with a message.
- This will continue until the value of the while-loop condition remains true. When this condition becomes false, the control passes back to the outer do-while loop.
- Similarly, the iteration of the do-while loop will continue until the outer condition, that is, doWhileLoop<=2, remains true.
- After completing both of the loop iterations, the program returns 0.
Q. Can we skip braces in C do-while loop syntax if there is only one statement in the body?
No, we can not skip curly brackets in the loop body or else the compiler will throw an error while compiling our code. This is because it not only marks the beginning and the ending of the code but also separates it from the looping condition, which is checked after code execution in a do-while loop.
We can skip the brackets in a for loop if the code body consists of only one statement. However, it is still recommended to use the brackets to avoid any errors. So, it is best practice to always follow the exact syntax while writing the code.
Code Example:
Output:
The value of n is 1
The value of n is 2
The value of n is 3
Explanation:
- In the example above, we use a do-while loop to print the value of variable n.
- At every iteration of the loop, we use a printf() statement to display the current value and then a postfix increment operator to update the value of the control variable.
- This section of the code is inside the curly brackets. After which, we check the while condition, i.e., n<=3. The loop will execute iteratively till this condition returns true.
- If we skip curly braces, then it will result in an error. You can go ahead and try the code example with and without the brackets for yourself.
Q. How can we stop an infinite loop in C?
Infinite loops, as is evident by the ane, will run indefinitely until they are terminated manually or by inserting a specific condition to make it happen. One such way to stop or terminate an infinite loop in C is the use of the break statement. The loop terminates immediately when it comes in contact with the break command.
Code Example:
Output:
Enter a Number : 3
Current Number 3
Current Number 2
Current Number 1
The loop has ended.
Explanation:
In the example above, we prompt the user to enter a value for the variable n. Then, we create an infinite while loop, where the base condition is 1. Inside this loop, we use a printf() function to display the value of n and reduce the value of n after every iteration. Normally, this loop will continue printing the value of n infinitely, i.e., even the negative values.
But we introduce an if-statement with a break statement. Here, the if-condition uses the equality relational operator to check if the value of n is equal to 0. When this condition is met, the loop terminates due to the break statement.
Q. Can I have multiple statements inside the do-while loop body?
Yes, you can use multiple statements inside the curly braces of the do-while loop. All the lines of code in between curly braces will be treated as the body of the loop, and these loop blocks will be executed in each traversal. Let's take a look at an example where we use multiple statements inside the do-while loop body.
Code Example:
Output:
1 2 3 4 5
Explanation:
- We begin by initializing an integer variable i inside the main() function to the value of 1.
- Next, we create a do-while loop that consists of two statements, i.e., one is a printf() statement, and the other is an updation statement.
- The printf() statement displays the value of the variable, and the updation statement updates the value of the control variable before moving to check the loop condition.
- At the end, the program terminates by returning zero.
Q. Are there any limitations or considerations when using a do-while loop in C?
Yes, when using a do-while loop in C, it's essential to consider potential pitfalls. They are-
- The loop guarantees at least one iteration, even if the condition check is initially false, which may lead to unnecessary code execution.
- There is a risk of unintentional infinite loops if the loop condition is not properly updated within the loop statement body.
- Careful attention to variable initialization and scoping is necessary, especially in nested loops, to avoid unintended side effects.
- Excessive nesting can impact code readability, and the do-while loop is less commonly used than other loop constructs, emphasizing the importance of selecting the appropriate loop based on specific programming needs.
With these pointers on using a do-while loop in C, you must be able to make the most of these constructs in your codes.
Here are a few other topics you must be familiar with:
- Logical Operators In C Explained (Types With Examples)
- Ternary (Conditional) Operator In C Explained With Code Examples
- Identifiers In C | Rules For Definition, Types, And More!
- Tokens In C | A Complete Guide To 7 Token Types (With Examples)
- Constant In C | How To Define & Its Types Explained With Examples