#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Loops

Understanding While loop in C

What is a while Loop?

The while loop repeats a block of code as long as a given condition remains true. It's an entry-controlled loop — the condition is checked before each iteration.

Syntax

while (condition) {
    // statements
}

Example

int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}
// Output: 1 2 3 4 5

If the condition is false to begin with, the loop body never executes.

A Complete Program and Its Output

Here is a full, runnable version of a counting loop. Notice the three parts every counter-driven while loop needs: initialise the variable, test it, and update it inside the body.

#include <stdio.h>

int main(void) {
    int i = 1;              /* 1. initialise */

    while (i <= 5) {        /* 2. test */
        printf("%d ", i);
        i++;                /* 3. update */
    }

    printf("\nLoop finished, i = %d\n", i);
    return 0;
}

Output:

1 2 3 4 5
Loop finished, i = 6

Trace it once by hand. When i is 5, the test passes, 5 is printed, and i becomes 6. The next test, 6 <= 5, is false, so control jumps to the line after the closing brace. That is why the final value is 6, not 5.

Worked Example: Sum of Digits

The while loop shines when you do not know in advance how many times to repeat. Adding the digits of a number is a classic case, because the number of digits depends on the input.

#include <stdio.h>

int main(void) {
    int n, sum = 0;

    printf("Enter a positive number: ");
    scanf("%d", &n);

    while (n > 0) {
        sum += n % 10;   /* take the last digit  */
        n /= 10;         /* drop the last digit  */
    }

    printf("Sum of digits = %d\n", sum);
    return 0;
}

For input 4721, the loop runs four times: it adds 1, then 2, then 7, then 4, giving 14. When n becomes 0, the condition fails and the loop ends.

The same pattern is useful for reading input until the user types a sentinel value, waiting for a sensor reading, or processing characters until the end of a string is reached.

Choosing Between while, for and do-while

LoopCondition checkedBest when
forBefore each passThe number of iterations is known, such as walking an array
whileBefore each passYou repeat until something happens, and zero passes is acceptable
do-whileAfter each passThe body must run at least once, such as showing a menu

You can also write while (1) for a deliberate infinite loop and leave it with break when a condition inside the body is met. Use continue to skip the rest of the current pass and go back to the test.

Bugs to Watch Out For

  • A stray semicolon. while (i <= 5); creates an empty loop body. If i starts at 1, the program hangs forever.
  • Forgetting the update. Without i++, the condition never changes and the loop never ends.
  • Uninitialised variables. Testing a variable that was never given a value leads to unpredictable behaviour.
  • Off-by-one conditions. Using < where you meant <= skips the last value.
  • Comparing floats for equality. while (x != 1.0) may never be false because of rounding; compare with a range instead.

Before running any while loop, ask yourself: where is the variable set, where does it change, and which value will finally make the condition false?

Ready to master real-world C Programming development?

Learn C Programming hands-on with mentor-led, live sessions.

Explore Course