while loop in C with example



Before know about the while loop we must know about the "loop". In the programming language loops are used to execute the same line of code multiple times.

while loop concept is same as the for loop. like code execute until the given condition isn't false inside the while loop.



Where we use while loop in C:


Have you think  we all know for loop is a mostly used loop in the C programming languages. then why we need the while loop and why the concept introduce of while loop?
because we can use for loop only where we know the number of steps or number of iterations but we all know in all cases we don't have any idea of the number of iterations like sum of digits of a number etc.
So solving these kind of problem we need the while loop.

Syntax of while loop in C:


while (condition statement)
{
//code to be executed repeatedly
// Increment (++) or Decrement (--) Operation
}


Flow chart of while loop in C:



While loop in C


while loop in C with example:


problem statement: We have a number N and the problem statement says find the sum of digits in the N using C programming language.


Input:

456

Output:

sum of digits in given number is: 15


  1. #include<stdio.h>  
  2.  int main()    
  3. {    
  4. int n,sum=0,m;    
  5. printf("Enter a number:");    
  6. scanf("%d",&n);    
  7. while(n>0)    
  8. {    
  9. m=n%10;    
  10. sum=sum+m;    
  11. n=n/10;    
  12. }    
  13. printf("Sum of digits in given number is=%d",sum);    
  14. return 0;  
  15. }   
 

Explanation:

  • First we take the number form the user in our program.
  • Then here we use while loop because in this case we don't have any idea of the number of steps.
  • In the last we print the sum of digits.

problem statement : In this problem statement we need to write a program in C language to print the table of any number till 10 counts.


  1. #include<stdio.h>  
  2. int main(){    
  3. int i=1,number=0,b=9;    
  4. printf("Enter a number: ");    
  5. scanf("%d",&number);    
  6. while(i<=10){    
  7. printf("%d \n",(number*i));    
  8. i++;    
  9. }    
  10. return 0;  
  11. }