The while Loop In C.

By Shakib Ansari | Date: Sat, May 3, 2025

The while loop ek sabse simplest loop hoti hai sabhi loops mein. Ham while loops ka use bahut hi frequently karte hai kiuki ye bahut hi easy hoti hai use karna. The basic format of the while statement is

while(test-condition)
{
        body of the loop
}

The while ek entry-controlled loop statement hai. The while loop mein test-condition evaluate hoti hai aur agar test-condition true hai, to loop ki body execute hogi. Body execution ke baad, test-condition ek baar aur evaluate hogi aur agar ye ab bhi true hai to body again execute hogi. Ye process tab tak repeat hoga jab tak condition false nhi hoti aur false hone ke baad program control out of loop chala jayega. Loop exit hone ke baad program un statements ko run karega jo immediately loop ke baad hai. Loop mein ek ya ek se zyada statements ho sakti hai aur agar ek se zyada statements hai to curly braces needed hai nhi to agar ek hi statement hai to curly braces avoid bhi kar sakte hai lekin curly braces lagana ek good prectice hai although ek statement hi kiyu na ho.

Example.

#include <stdio.h>
int main()
{
    int n = 1;  // Initialization 
    printf("Start The Loop ");
    while (n <= 10) // Testing 
    {
        printf("%d", n);
        n = n + 1; // Incrementing 
    }
    printf("End The Loop");
    return 0;
}
Output:
Start The Loop
1
2
3
4
5
6
7
8
9
10
End The Loop

Explaination:

Yaha par loop ki body 10 times execute hogi for n = 1, 2, 3, ..., 10, har baar ye 'n' ki value ko print karega aur 'n' ki value ko hi increment kar dega. Jab 'n' ki value 11 ho jayegi to condition false ho jaygi jisse program control loop se exit ho jayega aur immediate statement 'End The Loop' run kar dega. Yaha par 'n' variable counter or control variable kehlayga.


A program to Evaluate the equation y = xn when n is a non-negative integer

Intuition: Pehle variable y ko ham 1 se initialize karenge aur phir user se two values input lenge 'x' and 'n'. Phir ek condition test karenge while(n != 0) phir while ki body mein y = y * x; initialize kar denge aur har baar n ko 1 se decrement kar denge jisse y * x sirf 'n' times hi ho. Jab while condition false ho jayegi tab program ka control loop se exit ho jayega aur variable 'y' ko print kar denge.

#include <stdio.h>
int main(int argc, char const *argv[])
{
    float x, y = 1.0;
    int n;
    printf("Enter the value of x and n :");
    scanf("%f %d", &x, &n);
    while (n != 0)
    {
        y = y * x;
        n--;
    }
    printf("x to power n = %f", y);
    return 0;
}
Output:
Enter the value of x and n : 2.5 3
x to power n = 15.625000


About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments