C While Loop

๐Ÿ” C While Loop – Repeat Until a Condition Fails

The while loop in C runs a block of code as long as a specified condition is true. It’s great when you don’t know how many times the loop should run โ€” just give it a condition and let it roll!

๐Ÿ”น Syntax of while loop

while (condition) {
    // code to execute
}

๐Ÿ“ Example: Count from 1 to 5

This program prints numbers from 1 to 5 using a while loop.

#include <stdio.h>

int main() {
    int i = 1;

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

    return 0;
}

Try It Now

๐Ÿ“ Example: Print Even Numbers

This version prints odd numbers from 1 to 9

#include <stdio.h>

int main() {
    int i = 1;
    while (i <= 9) {
        if (i % 2 != 0) {
            printf("%d\n", i);
        }
        i++;
    }
    return 0;
}

Try It Now

๐ŸŽฏ Key Notes

  • The loop checks the condition before running the block.
  • If the condition is false on the first check, the loop won’t run at all.
  • Great for loops that depend on dynamic values like user input.

๐ŸŽ‰ Practice Time!

Try modifying the condition to count down, accept specific input ranges, or create a simple menu loop!