While Loop - C Tutorial

While Loop

C while loops statement allows to repeatedly run the same block of code, until a condition is met.

while loop is most basic loop in C programming. while loop has one control condition, and executes as long the condition is true. The condition of the loop is tested before the body of the loop is executed, hence it is called an entry-controlled loop.

Syntax of While loop

while (testExpression) 
{
     //Code to execute while the condition is true
}

Program To Find Sum of Digits of a Number Using While Loop

#include <stdio.h>
int main()
{
    int num, dsum = 0,r,n;
    printf("Enter the Number :");
    scanf("%d",&num);
    n=num;
    while(n!=0)
    {
        r = n % 10;
        dsum = dsum + r;
        n = n / 10;
    }
    printf("DigitSum of %d is %d", num, dsum);
}
Output - Program To Find Sum of Digits of a Number
Enter the Number :3234                                                                                                
DigitSum of 3234 is 12