While Loop in C
Syntax:
while(condition) { statement(s); }
Explanation:
The statement(s) enclosed in curly braces get executed until the condition evaluates to false. Here the condition means an expression or it can be any value.Key Points To Remember:
- While loop is control structure. That means we can control the flow of execution with this structure.
- This loop will not iterate if the condition is false initially.
- It is also called as entry controlled or top tested as the condition is checked at beging, before iterating the statement(s).
Use while loop:
The While loop is used to repeat a section or block of code an unknown number of times until a specific condition is met.That is, it is used when we do not know how many times we need to iterate the loop?
Example:
Problem:
Write a C program which accepts a number from user and displays how many times that number is divisible by 2.#include<stdio.h> void main() { int number,sum=0,original; printf("\n Enter any number:- "); scanf("%d",&number); // Accepting a number,storing it into 'number' variable original=number; // Storing the original number into 'original' variable while(number>0) { sum=sum+number%10; // Every time adding the last digit to sum number=number/10; } printf("\n The sum of the digits of %d is %d \n",original,sum); // Displaying the original number and sum of its digits }
Explanation:
We will see how the while loop works.Suppose user entered 456, we stored it in 'number' as well as in 'original' variable.
For the first iteration, we have number=456
the condition in while i.e number>0 is checked and yes 456>0 i.e the condition evaluates to true. Now the statements get executed as
- sum=sum+number%10;
i.e sum=0+456%10; as sum is initialized to 0 and number=456. i.e sum=0+6; i.e. sum=6; - Another statement is
i.e number=number/10;
i.e number=456/10; i.e number=45;
For second iteration,
- The first statement ,
sum=sum+number%10;
i.e sum=6+45%10; (values of number and sum are taken from previous iteration)
i.e sum=6+5; i.e sum=11; - Next is
number=number/10;
i.e number=45/10;
i.e number=4;
For the third iteration,
- The first statement ,
sum=sum+number%10;
i.e sum=11+4%10; (Values of sum and number are from previous iterations)
i.e sum=11+4;
i.e sum=15;
- Next is
number=number/10;
i.e number=4/10;
i.e number=0; as number is of integer data type so it will store only integers and not floating point numbers.
After the loop is over we are just displaying the original number along with sum of its digits.
Practice With These Programs:
- C program to count the digits of a number
- C program to check given number is Armstrong number or not
- C program to find the longest line
- C program to convert hexadecimal to binary