Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟢 Beginner  ·  Lesson 14

while and do-while Loop in C (with Programs)

In this lesson: Learn while and do-while loops in C with syntax, differences, dry run and programs like reverse number and sum of digits with output.

while Loop

The while loop repeats a block of code as long as its condition is true. Use it when you don't know in advance how many times the loop should run.

Syntax
while (condition) {
    // body
    // update variable (to avoid infinite loop!)
}

The condition is checked before each iteration. If the condition is false from the start, the body never executes.

Example 1: Print 1 to 5

C Language
#include <stdio.h>
int main() {
    int i = 1;            // Initialization (outside loop)
    while (i <= 5) {      // Condition
        printf("%d\\n", i);
        i++;              // Update (inside loop)
    }
    return 0;
}
1 2 3 4 5
Dry Run — dekhiye har step kaise chalta hai (i = 1 se shuru)
Stepi ki valueCondition: i <= 5Kya huai ab
111 <= 5 → trueprint 1i++ → 2
222 <= 5 → trueprint 2i++ → 3
333 <= 5 → trueprint 3i++ → 4
444 <= 5 → trueprint 4i++ → 5
555 <= 5 → trueprint 5i++ → 6
666 <= 5 → falseCondition false — loop yahin ruk gaya (STOP)—
💡 Ise aise samajhiye

Loop tab tak chalta hai jab tak i <= 5 sach hai. Har baar i ek badhta hai. Jaise hi i 6 hua, condition jhoothi ho gayi aur loop ruk gaya — isliye 6 print nahi hua.

Example 2: Sum until User Enters 0

C Language
#include <stdio.h>
int main() {
    int num, sum = 0;
    printf("Enter numbers (0 to stop):\\n");
    scanf("%d", &num);
    while (num != 0) {
        sum += num;
        scanf("%d", &num);
    }
    printf("Total sum = %d\\n", sum);
    return 0;
}
Enter numbers (0 to stop): 5 10 3 7 0 Total sum = 25

Example 3: Reverse Digits of a Number

C Language
#include <stdio.h>
int main() {
    int num, rev = 0;
    printf("Enter number: ");
    scanf("%d", &num);
    while (num != 0) {
        int digit = num % 10;
        rev = rev * 10 + digit;
        num /= 10;
    }
    printf("Reversed: %d\\n", rev);
    return 0;
}
Enter number: 12345 Reversed: 54321

do-while Loop

The do-while loop is similar to while, but the body executes at least once because the condition is checked after the body.

Syntax
do {
    // body (runs at least ONCE)
} while (condition);  // Note: semicolon here!

Example: Menu-Driven Program

C Language – Menu with do-while
#include <stdio.h>
int main() {
    int choice;
    do {
        printf("\\n1. Add\\n2. Subtract\\n3. Exit\\nEnter choice: ");
        scanf("%d", &choice);
        if (choice == 1)      printf("Adding...\\n");
        else if (choice == 2) printf("Subtracting...\\n");
        else if (choice == 3) printf("Goodbye!\\n");
        else                   printf("Invalid choice!\\n");
    } while (choice != 3);
    return 0;
}
⚠️ Don't forget the semicolon!

The do-while loop requires a semicolon after the closing while (condition);. Forgetting it causes a compile error.

while vs do-while vs for

Featureforwhiledo-while
Condition checkBefore (entry-controlled)Before (entry-controlled)After (exit-controlled)
Min executions0 (if condition false)0 (if condition false)1 (always)
Best used whenCount knownCount unknownMust run at least once
Update locationIn for() headerInside bodyInside body

Infinite Loop

A loop that never ends. Use break to exit from inside.

C Language
while (1) {          // Always true
    int x;
    scanf("%d", &x);
    if (x == 0) break;  // Exit when 0 entered
    printf("You entered: %d\\n", x);
}

Summary

  • while — condition checked before body; body may never run
  • do-while — body runs first, condition checked after; runs at least once
  • do-while needs semicolon: } while (cond);
  • Use while for unknown count, for for known count
  • Always update the loop variable to avoid infinite loops

Authoritative References

References reviewed on 14 August 2026. Programs and outputs are original teaching examples.

Frequently Asked Questions

What is the difference between while and do-while loop in C?
A while loop checks its condition before running the body, so if the condition is false at the start the body never runs. A do-while loop checks the condition after running the body, so the body always runs at least once. That guaranteed first run is the key difference.
When should I use a while loop instead of a for loop?
Use a while loop when you do not know in advance how many times you will repeat — for example reading input until the user types "quit". A for loop suits counting a known number of times, where the counter, condition and step fit neatly on one line.
What is an infinite loop in C?
An infinite loop is one whose condition never becomes false, so it runs forever — such as while (1). Sometimes this is intentional (a program that waits for events), but usually it is a bug caused by forgetting to update the variable in the condition.
Does a do-while loop always run at least once?
Yes. Because a do-while loop tests its condition only after executing the body, the body runs at least one time even if the condition is false from the very beginning. This makes it ideal for menus and input validation.
How do you avoid an accidental infinite while loop?
Make sure something inside the loop changes the variable used in the condition, so the condition eventually becomes false. Forgetting to increment a counter or update a flag is the most common cause of an unintended infinite loop.
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicbreak, continue & goto Your progress: 14 / 67 (21%) · Lesson 15 / 67 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free