Tutorial Playlist
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
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...