Tutorial Playlist
132 Lessons1. Introduction to C Tutorial
2. Addition of Two Numbers in C
3. Anagram Program in C
4. Armstrong Number in C
5. Array in C
6. Array of Pointers in C
7. Array of Structure in C
8. C Program to Find ASCII Value of a Character
9. Assignment Operator in C
10. Binary Search in C
11. Binary to Decimal in C
12. Bitwise Operators in C
13. Boolean in C
14. C Compiler for Mac
15. C Compiler for Windows
16. C Function Call Stack
17. C Language Download
18. Operators in C
19. C/C++ Preprocessors
20. C Program for Bubble Sort
21. C Program for Factorial
22. C Program for Prime Numbers
23. C Program for String Palindrome
24. C Program to Reverse a Number
25. Reverse a String in C
26. C string declaration
27. String Input Output Functions in C
28. Calculator Program in C
29. Call by Value and Call by Reference in C
30. Ceil Function in C
31. Coding Vs. Programming
32. Command Line Arguments in C/C++
33. Comments in C
34. Compilation process in C
35. Conditional Statements in C
36. Conditional operator in the C
37. Constant Pointer in C
38. Constants in C
39. Dangling Pointer in C
40. Data Structures in C
41. Data Types in C
42. Debugging C Program
43. Convert Decimal to Binary in C
44. Define And include in C
45. Difference Between Arguments And Parameters
46. Difference Between Compiler and Interpreter
47. Difference Between If Else and Switch
48. Do While Loop In C
Now Reading
49. Double In C
50. Dynamic Array in C
51. Dynamic Memory Allocation in C
52. Enumeration (or enum) in C
53. Evaluation of Arithmetic Expression
54. Factorial of A Number in C
55. Features of C Language
56. Fibonacci Series Program in C Using Recursion
57. File Handling in C
58. For Loop in C
59. Format Specifiers in C
60. Functions in C
61. Function Pointer in C
62. goto statement in C
63. C Hello World Program
64. Header Files in C
65. Heap Sort in C Program
66. Hello World Program in C
67. History of C Language
68. How to compile a C program in Linux
69. How to Find a Leap Year Using C Programming
70. Identifiers in C
71. If Else Statement in C
72. If Statement in C
73. Implementation of Queue Using Linked List
74. Increment and decrement operators in c
75. Input and Output Functions in C
76. How To Install C Language In Mac
77. Jump Statements in C
78. Lcm of Two Numbers in C
79. Length of an Array in C
80. Library Function in C
81. Linked list in C
82. Logical Operators in C
83. Macros in C
84. Matrix multiplication in C
85. Nested if else statement in C
86. Nested Loop in C
87. One Dimensional Array in C
88. Operator Precedence and Associativity in C
89. Overflow And Underflow in C
90. Palindrome Program in C
91. Pattern Programs in C
92. Pointer to Pointer in C
93. Pointers in C: A Comprehensive Tutorial
94. Pre-increment And Post-increment
95. Prime Number Program in C
96. Program for Linear Search in C
97. Pseudo-Code In C
98. Random Access Files in C
99. Random Number Generator in C
100. Recursion in C
101. Relational Operators in C
102. Simple interest program in C
103. Square Root in C
104. Stack in C
105. Stack Using Linked List in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
112. String Comparison in C
113. String Functions in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
118. Structure of C Program
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
122. Toupper Function in C
123. Transpose of a Matrix in C
124. Two Dimensional Array in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
129. User Defined Functions in C
130. What is Variables in C
131. Is C language case sensitive
132. Fibonacci Series in C
Programming often involves repeating tasks. In the C programming language, the 'Do While' loop is one tool that helps with this. Think of it as a circle. First, it performs a task. Then, it checks for a condition. If the condition is true, it goes back and does the task again. If the condition is false, it exits the circle and moves on.
Imagine asking your computer to print numbers. You'd like it to start at 1 and stop at 10. A 'Do While' loop can handle this task. First, it'll print the number 1. Then, it'll check: "Is this number less than 10?" Because 1 is less than 10, the loop will continue to print the following number, 2, and so on. When it reaches 10 and checks again, it will stop.
Later in this Do While Loop In C guide, we will provide a Do while loop example to further show how it works. By understanding the 'Do While' loop, you'll have another powerful tool in your programming toolkit.
Sometimes, we need actions to happen at least once before checking if they should continue when coding. The do...while Loop in C is perfect for this. Unlike other loops where the condition is checked first, this loop acts first and then checks the condition.
The beauty of the do...while Loop in C is that even if the condition is false from the start, the action inside the loop will run at least once. This is where the Do while loop syntax comes into play. The syntax helps you write the loop correctly and ensures your program behaves as expected.
We will learn more about the specifics of this loop in the coming sections by understanding the syntax and how the do...while Loop in C functions, you'll be better equipped to handle scenarios where this loop proves most beneficial.
The do-while loop in C is a power flow statement. It's a tool that programmers use when they want a set of tasks to be done at least once and then repeated based on a condition. The unique thing about the do-while loop is that it checks the condition after executing the block of statements and ensures the code inside the loop runs at least once.
CODE:
do {
// Block of statements;
} while (condition);
Example
Let's say we want a program that asks a user for a password. The program should ask again if the password is wrong.
Input:
#include <stdio.h>
#include <string.h>
int main() {
char password[10];
do {
printf("Enter the password: ");
scanf("%s", password);
} while (strcmp(password, "secret123") != 0);
printf("Password accepted!");
return 0;
}
The loop will keep asking for the password until "secret123" is entered. Only then will it display "Password accepted!" and exit the loop.
Output:
The do-while loop in C has a simple structure. It begins with the do keyword and continues with a series of statements enclosed by curly braces.
After this block, the while keyword appears, followed by a condition in parentheses and, finally, a semicolon to end the loop.
CODE:
do {
// Statements to be executed;
} while (condition);
Key Points
1. The statements inside the do block will always run at least once.
2. After executing the statements, the loop will check the condition.
3. The loop will run again if the condition is true.
4. The loop stops, and the program moves on to the next part if the condition is false.
Example
Suppose we want a program that prints numbers from 1 to 5. Here's how we can do it using a do...while loop
Input:
#include <stdio.h>
int main() {
int count = 1;
do {
printf("%d\n", count);
count++;
} while (count <= 5);
return 0;
}
The loop will print 1 and then increase the count by 1. Then it will check if the count is less than or equal to 5. The loop runs again if the case is true. This continues until the count is no longer less than or equal to 5.
Output:
We need a few simple steps to use the do-while loop in C. Let us go over them together.
Ensure you set up any variables you will use before you start the loop. This includes counters or variables you will check in your loop's condition.
Example
int count = 1;
Begin with the do keyword, then the set of statements you want to run. After the block, use the while keyword to specify the condition for continuing the loop.
CODE:
do {
// Your code here;
} while (condition);
Within the curly braces after do, write the statements you want to execute. Remember that these statements will always run at least once.
After the do block, set the condition in the while part of the loop. This condition determines if the loop should run again.
Example
Let's use the do...while loop to create a program that asks a user to guess a number between 1 and 10:
Input:
#include <stdio.h>
int main() {
int guessedNumber;
int correctNumber = 7;
do {
printf("Guess a number between 1 and 10: ");
scanf("%d", &guessedNumber);
} while (guessedNumber != correctNumber);
printf("Congrats! You guessed the right number.");
return 0;
}
The loop will keep asking the user to guess a number until they guess 7 (the correct number). The loop stops once they do, and the program congratulates the user.
Output:
Understanding how the do-while loop works is important for effective coding. Let's take the mechanics step-by-step.
The loop starts by executing the block of code inside the do section. This is the fundamental difference from other loops. This block runs at least once, irrespective of the condition.
The loop checks the condition specified after the while keyword once the do block finishes. We return to the do block and run it again if this condition evaluates to true.
This process of executing the block and checking the condition continues until the condition becomes false. When that happens, the loop exits, and the program proceeds to any code after the loop.
Example-
Imagine you have a digital piggy bank, and you want to keep adding coins until you reach a specific amount.
Input:
#include <stdio.h>
int main() {
int totalAmount = 0;
int coin;
do {
printf("Add a coin to your piggy bank (1, 5, 10, or 25): ");
scanf("%d", &coin);
totalAmount += coin;
} while (totalAmount < 100);
printf("You've saved up 100 or more units in your piggy bank!\n");
return 0;
}
The program will keep prompting users to add coins until the total amount reaches or exceeds 100. The loop ensures the user gets at least one chance to add a coin. Then, the program checks if the total is still less than 100. If it is, the program asks for another coin; otherwise, it congratulates the user.
Output:
Start
|
v
do -----------> Execute statements
|
v
Check condition -----> No --> Exit loop
|
v
Yes
|
v
Return to "do"
A nested do-while loop means you have a do-while loop inside another do-while loop. The inner loop completes all its iterations before the outer loop proceeds to its next iteration.
Let's illustrate this with a program. Imagine we want to print a multiplication table for numbers 2 to 4:
Input:
#include <stdio.h>
int main() {
int i = 2, j;
do {
j = 1; // Reset j for each outer loop iteration
do {
printf("%d x %d = %d\n", i, j, i*j);
j++;
} while (j <= 10); // Inner loop, which prints the multiplication for numbers 1 to 10
printf("\n"); // For separating tables
i++;
} while (i <= 4); // Outer loop, which changes the multiplier from 2 to 4
return 0;
}
Output:
In the above example:
1. Counting Down from 10 to 1:
Input:
#include <stdio.h>
int main() {
int counter = 10;
do {
printf("%d\n", counter);
counter--;
} while (counter > 0);
printf("Blast off!\n");
return 0;
}
Output:
2. Password Retry System
Input:
#include <stdio.h>
#include <string.h>
int main() {
char password[20];
int attempts = 0;
do {
printf("Enter your password: ");
scanf("%s", password);
attempts++;
if(strcmp(password, "my_password") == 0) {
printf("Access granted!\n");
return 0;
} else if(attempts == 3) {
printf("Three incorrect attempts. Access denied.\n");
return 0;
} else {
printf("Incorrect password. Try again.\n");
}
} while (1); // This is an infinite loop, but it will break out when correct password is entered or after three failed attempts.
return 0;
}
Output:
Feature | while Loop | do...while Loop |
Definition | Starts with the condition check before executing the loop's body. | Executes the loop's body first before checking the condition. |
Execution | The loop's body might never execute if the initial condition is false. | The loop's body will execute at least once, even if the condition is false initially. |
Syntax | c while(condition) { // statements } | c do { // statements } while(condition); |
Use Case | Useful when you need to check a condition before any execution. | Useful when you want to ensure the loop's body runs at least once before checking the condition. |
Example Scenario | Checking if a user is logged in before displaying profile details. | Displaying an error message and then checking if it should be displayed again. |
The main distinction between the two loops is the order of operation: the while loop checks the condition before executing its body and the do...while loop ensures at least one execution before checking the condition. The choice between them depends on the needs of your program.
We have discussed the mechanics of the do-while loop in C in this Do While loop in C tutorial. We discovered that the unique characteristic of the do...while loop is its guarantee to execute its body at least once. This sets it apart from the traditional while loop, which checks the condition before the loop body gets a chance to run.
We showcased how to effectively use the do...while loop through various examples. Our comparative table highlighted the key differences in syntax and use cases between while and do...while loops. This will make it easier to decide which loop suits a situation.
1. What's the purpose of a loop in programming?
Loops let a program do a task repeatedly. They help automate repetitive tasks and make code efficient.
2. How does a for loop differ from do...while?
A for loop sets initialization, condition, and update in one line. The do...while loop focuses on post-execution condition checks.
3. Why would someone choose do...while over other loops?
Use do...while when the task must run at least once. You can use it where you need to get the user's input and then check it.
4. How do you exit a loop prematurely?
Use the break statement. It stops the loop immediately and skips any code that follows it inside the loop.
5. What happens if the condition in do...while never becomes false?
The loop will run indefinitely and create an infinite loop. Ensure the condition can become false to avoid this.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...