while Loop in C Programming

Flow of a while loop in C

A while loop checks its condition before each iteration. The body runs only while that condition remains true, so it may run zero times.

while Loop Syntax Top ↑

while (condition) {
    // statements
    // update something used by the condition
}

Print 1 to 5 Top ↑

#include <stdio.h>

int main(void) {
    int i = 1;

    while (i <= 5) {
        printf("%d\n", i);
        i++;
    }

    return 0;
}

Output

1
2
3
4
5

Avoid Infinite Loops Top ↑

If the condition never becomes false, the loop does not end. For example, this loop never changes i:

int i = 1;

while (i <= 5) {
    printf("%d\n", i);
    // Missing i++ means the condition never changes.
}

Infinite loops can be intentional in event-driven or embedded programs, but beginner loops should normally make the terminating condition clear.

break and continue Top ↑

#include <stdio.h>

int main(void) {
    int i = 1;

    while (i <= 5) {
        if (i == 4) {
            break;
        }
        printf("%d\n", i);
        i++;
    }

    return 0;
}

Output

1
2
3
#include <stdio.h>

int main(void) {
    int i = 0;

    while (i < 5) {
        i++;

        if (i == 3) {
            continue;
        }

        printf("%d\n", i);
    }

    return 0;
}

Output

1
2
4
5

When using continue in a while loop, update the loop-control variable before the continue path if needed. Otherwise the loop can become infinite.

Decrement by 10 Top ↑

#include <stdio.h>

int main(void) {
    int i = 50;

    while (i >= 0) {
        printf("%d\n", i);
        i -= 10;
    }

    return 0;
}

Output

50
40
30
20
10
0

Reverse a String Top ↑

#include <stdio.h>
#include <string.h>

int main(void) {
    char text[] = "plus2net";
    size_t length = strlen(text);

    while (length > 0) {
        putchar(text[length - 1]);
        length--;
    }
    putchar('\n');

    return 0;
}

Output

ten2sulp

Sum with a while Loop Top ↑

#include <stdio.h>

int main(void) {
    int sum = 0;
    int i = 1;

    while (i <= 5) {
        sum += i;
        i++;
    }

    printf("Sum: %d\n", sum);
    return 0;
}

Input Validation with while Top ↑

#include <stdio.h>

int main(void) {
    int number;

    printf("Enter a number from 1 to 10: ");
    while (scanf("%d", &number) == 1 && (number < 1 || number > 10)) {
        printf("Out of range. Enter 1 to 10: ");
    }

    if (number >= 1 && number <= 10) {
        printf("Valid number: %d\n", number);
    } else {
        printf("Invalid input.\n");
    }

    return 0;
}

See another example: keep adding user-entered numbers until 0 is entered.





plus2net.com



21-01-2020

Write a program that finds the sum of even numbers between zero and twenty use while loop



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer