WHAT'S NEW?
Loading...

while Loop in C Programming (With Examples)

While loops are similar to for loops, but have less functionality. A while loop continues executing the while block as long as the condition in the while remains true.
Syntax: 
           while(condition){
                     statement(s); 
          }
The condition is evaluated and if the condition is true, then the given statements is executed. After execution of the body once, the condition is again evaluated and if it is true, the statements is again executed. This process of repeated execution of the body continues until the test-condition finally becomes false and thecontrol is immediately after the body of the loop.
Example: WAP to print the natural numbers from 1 to 10 using while loop. 

#include<stdio.h>
void main(){
 int n=1; 
 while(n<=10){
  printf("%d,  ",n); 
  n++; 
 }
 getch(); 
}
Output
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

Example 2: WAP to print the Even numbers in descending order from 20 to 1 using while loop.
#include<stdio.h>
void main(){
 int n=20; 
 while(n>=1){
  printf("%d,  ",n); 
  n=n-2; 
 }
 getch(); 
}
Output
20, 18, 16, 14, 12, 10, 8, 6, 4, 2,

Example 3: WAP to print the multiplication table of given number using while loop
#include<stdio.h>
void main(){
 int n, i=1; 
 printf("Enter any Number : "); 
 scanf("%d",&n); 
 while(i<=10){
  printf("%d x %d = %d\n", n, i, n*i); 
  i++; 
 }
 getch(); 
}
Output
Enter any Number : 23
23 x 1 = 23
23 x 2 = 46
23 x 3 = 69
23 x 4 = 92
23 x 5 = 115
23 x 6 = 138
23 x 7 = 161
23 x 8 = 184
23 x 9 = 207
23 x 10 = 230

Example 4: WAP to get an integer number n and calculate and print the sum of numbers from 1 to n using while loop.
#include<stdio.h>
void main(){
 int n, sum=0;
 printf("Enter any Number : "); 
 scanf("%d",&n); 
 while(n>=1){
  sum=sum+n; 
  n--; 
 }
 printf("The Sum is : %d",sum); 
 getch(); 
}
Output
Enter any Number : 50
The Sum is : 1275

Example 5:Write a program to calculate the factorial of given number. 

#include<stdio.h>
void main(){
 int n, f=1;
 printf("Enter any Number : "); 
 scanf("%d",&n); 
 while(n>=1){
  f=f*n; 
  n--; 
 }
 printf("The Factorial is : %d", f); 
 getch(); 
}
Output
Enter any Number : 7
The Factorial is : 5040

0 comments:

Post a Comment