do-while Loop in C Programming
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

do-while Loop in C Programming – Explained with Examples

📑 On this page:
  • Introduction
  • What is a Loop?
  • What is a do-while Loop?
  • Advantages of do-while Loop
  • Disadvantages of do-while Loop
  • Flowchart of do-while Loop
  • Syntax of do-while Loop
  • Menu Driven Program Example
  • Sum and Average Example
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • What a loop is and why we use loops in C programming
  • How the do-while loop works with real examples
  • Where to use do-while loops in real applications
  • How to write a menu driven program using do-while
  • Complete program examples with explanations

Introduction

In this tutorial, we will learn what a do-while loop is in C programming.

Before learning the do-while loop, it is important to understand what a loop is. Once the concept of loops is clear, learning the do-while loop becomes much easier.

What is a Loop?

A loop in C is used when we want to execute the same block of code repeatedly. Instead of writing the same statements multiple times, we use a loop to automate repetition. The loop continues to execute as long as a specified condition remains true.

💡 Think of it like this: Imagine you need to print your name 10 times. Without a loop, you would write the printf() statement 10 times. With a loop, you write it just once, and the loop repeats it 10 times.

What is a do-while Loop in C?

A do-while loop is a looping statement that executes the statements inside the loop at least once, even if the condition is false.

The statements inside the do block execute first. After execution, the condition is evaluated. If the condition is true, the loop executes again. Otherwise, the loop terminates.

Since the condition is checked after executing the loop body, the do-while loop is also known as a post-tested loop.

Where is a do-while Loop Used?

The do-while loop is mainly used when a block of code must execute at least once before checking a condition.

It is commonly used in:

  • ATM menu-driven applications
  • Online shopping applications
  • Spell checking tools
  • Text editors such as Notepad, MS Word, and Sublime Text
  • Menu-based software where the user decides whether to continue or exit

Advantages of Using do-while Loop in C Programming

1. Simple and easy to understand — The syntax is beginner-friendly

2. Ensures the loop body executes at least once — Perfect for menu-driven applications

3. Repeats execution automatically — While the condition remains true

4. Useful for interactive and menu-driven applications

Disadvantages of Using do-while Loop in C Programming

1. Infinite loop risk: If the loop condition always remains true, an infinite loop occurs

2. Incorrect exit conditions — May produce unexpected results

3. Care must be taken — While writing the condition to avoid logical errors

Flowchart of do-while Loop

The flowchart of a do-while loop works as follows:

Visual flowchart of do while loop in C with execution steps

Step-by-step explanation:

  1. Control enters the do block
  2. The statements inside the loop execute without checking any condition
  3. After execution, the condition is evaluated
  4. If the condition is true, control returns to the beginning of the loop
  5. The process repeats until the condition becomes false
  6. Once the condition is false, execution continues with the statements after the loop

Syntax of do-while Loop in C

The do-while loop consists of four important parts:

/* Declaration or Initialization */
int i = 1;

do {
    /* Loop Body (Instructions) */
    printf("Value: %d\n", i);
    
    /* Update Expression */
    i++;
} while (i <= 5);  /* Condition */

Let's break down each part:

🔹 Declaration or Initialization: Variables used inside the loop are declared and initialized before the loop starts. Proper initialization ensures correct execution.

🔹 Loop Body (Instructions): The loop body contains the statements that perform the required task. These statements execute every time the loop runs.

🔹 Update Expression: The update expression modifies the loop control variable, usually by incrementing or decrementing it. It determines how many times the loop executes.

🔹 Condition: The condition is evaluated after the loop body executes. If it evaluates to true, the loop continues; otherwise, it terminates.

⚠️ Note: A semicolon ; is mandatory after the while(condition) statement. Forgetting it will cause a syntax error.

Menu-Driven Program Using do-while Loop

The do-while loop is commonly used in menu-driven applications.

In a typical menu-driven program:

  • Variables are declared before the loop begins
  • The menu options are displayed
  • The user selects an option
  • The corresponding operation is executed
  • The user is asked whether they want to continue
  • If the user chooses to continue, the menu is displayed again
  • Otherwise, the program exits

This approach allows users to perform multiple operations without restarting the program.

Here's a complete example of an ATM-style menu:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char choice;
    int option;
    
    do {
        // Display menu options
        printf("\n=== ATM MENU ===\n");
        printf("1. Withdrawal\n");
        printf("2. Balance Enquiry\n");
        printf("3. Deposit\n");
        printf("4. Transfer Money\n");
        printf("5. Change PIN\n");
        printf("6. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &option);
        
        // Process user choice
        switch(option) {
            case 1:
                printf("✅ You selected: Withdrawal\n");
                break;
            case 2:
                printf("✅ You selected: Balance Enquiry\n");
                break;
            case 3:
                printf("✅ You selected: Deposit\n");
                break;
            case 4:
                printf("✅ You selected: Transfer Money\n");
                break;
            case 5:
                printf("✅ You selected: Change PIN\n");
                break;
            case 6:
                printf("Thank you for using our ATM!\n");
                exit(0);
                break;
            default:
                printf("❌ Invalid choice! Please select 1-6.\n");
        }
        
        // Ask if user wants to continue
        printf("\nDo you want to continue? (y/n): ");
        scanf(" %c", &choice);
        
    } while(choice == 'y' || choice == 'Y');
    
    printf("Thank you for visiting!\n");
    return 0;
}

Sample Output:

=== ATM MENU ===
1. Withdrawal
2. Balance Enquiry
3. Deposit
4. Transfer Money
5. Change PIN
6. Exit
Enter your choice: 2
✅ You selected: Balance Enquiry

Do you want to continue? (y/n): y

=== ATM MENU ===
1. Withdrawal
2. Balance Enquiry
3. Deposit
4. Transfer Money
5. Change PIN
6. Exit
Enter your choice: 6
Thank you for using our ATM!

Explanation:

  1. We declare two variables: option (int) and choice (char)
  2. The do-while loop starts and shows the menu
  3. User enters a choice (like 2 for Balance Enquiry)
  4. The switch statement runs the matching case
  5. After the switch, we ask if the user wants to continue
  6. If user enters 'y' or 'Y', the loop runs again
  7. If user enters 'n' or 'N', the loop ends

Program to Find Total and Average of First N Natural Numbers Using do-while Loop

This program calculates both the total and the average of the first N natural numbers.

Working of the Program:

  • Required variables are declared and initialized
  • The program accepts the value of N from the user
  • The do-while loop starts execution
  • During each iteration, the current value is added to the total
  • The loop control variable is updated
  • The loop continues until all numbers from 1 to N have been processed
  • After the loop finishes, the average is calculated by dividing the total by N
  • Finally, the total and average are displayed
#include <stdio.h>

int main() {
    int n, i = 1;
    int sum = 0;
    float average;
    
    // Ask user for input
    printf("Enter the value of n: ");
    scanf("%d", &n);
    
    // Calculate sum using do-while loop
    do {
        sum = sum + i;   // Add current number to sum
        i++;              // Move to next number
    } while (i <= n);
    
    // Calculate average
    average = (float)sum / n;
    
    // Display results
    printf("Sum of first %d numbers: %d\n", n, sum);
    printf("Average of first %d numbers: %.2f\n", n, average);
    
    return 0;
}

Sample Output:

Enter the value of n: 10
Sum of first 10 numbers: 55
Average of first 10 numbers: 5.50

Explanation:

  1. We declare variables: n (user input), i = 1 (counter), sum = 0, and average
  2. User enters the value of n (like 10)
  3. The do-while loop starts and adds i to sum
  4. Then i++ increases the counter by 1
  5. The loop runs until i becomes greater than n
  6. After the loop, we calculate the average
  7. The (float) converts sum to float for accurate division
  8. Finally, we display the sum and average

💻 Practice Exercise

Challenge: Write a program that asks the user to enter numbers. The program should keep asking until the user enters 0. Then display the sum of all entered numbers.

🔍 Click to Show Solution
#include <stdio.h>

int main() {
    int num, sum = 0;
    
    printf("Enter numbers (0 to stop):\n");
    
    do {
        scanf("%d", &num);
        sum = sum + num;
    } while (num != 0);
    
    printf("Sum of all numbers: %d\n", sum);
    return 0;
}

📝 Summary

  • A do-while loop always executes at least once
  • The loop condition is checked after executing the loop body
  • It is also known as a post-tested loop
  • It is especially useful in menu-driven and interactive applications
  • Proper initialization, update expressions, and loop conditions are necessary to avoid infinite loops and logical errors

Frequently Asked Questions About do-while Loop in C

1. What is the difference between while loop and do-while loop?

The main difference is that a while loop checks the condition first – if it's false, the loop never runs. A do-while loop runs the code first, then checks the condition – so it always runs at least once.

2. When should I use a do-while loop?

Use a do-while loop when you need the code to run at least once, like in menu driven programs, user input validation, or games where you need to show options before asking the user to continue.

3. Can a do-while loop run forever?

Yes! If the condition is always true, the loop will run forever. This is called an infinite loop. For example, if you write while(1) or while(i < 10) but never update i, the loop will never end.

4. Is the semicolon after while required in do-while?

Yes! The semicolon ; after while(condition) is required. Without it, the compiler will show a syntax error. This is one of the most common mistakes beginners make.

5. Can I use break and continue in do-while loop?

Yes, you can use both break and continue in a do-while loop. break exits the loop immediately. continue skips the rest of the current iteration and jumps to the condition check.

💡 Tip: When writing a do-while loop, always make sure the update expression changes the variable used in the condition. Otherwise, you might create an infinite loop.

📖 Related Tutorials

  • while Loop in C - Complete Guide
  • for Loop in C - Complete Guide
  • goto Statement in C
  • Introduction to Loops in C

Previous Topic: -->> goto statement in C   ||   Next topic: -->> while loop in C


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.