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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
while (condition) {
// code to execute
}
while (condition) { // code to execute }
while (condition) {
    // code to execute
}

📝 Example: Count from 1 to 5

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("Number: %d\n", i);
i++;
}
return 0;
}
#include <stdio.h> int main() { int i = 1; while (i <= 5) { printf("Number: %d\n", i); i++; } return 0; }
#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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#include <stdio.h>
int main() {
int i = 1;
while (i <= 9) {
if (i % 2 != 0) {
printf("%d\n", i);
}
i++;
}
return 0;
}
#include <stdio.h> int main() { int i = 1; while (i <= 9) { if (i % 2 != 0) { printf("%d\n", i); } i++; } return 0; }
#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!