🟢 Beginner  ·  Lesson 14

while & do-while Loop

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

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

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.