WHAT'S NEW?
Loading...

do while Loop in C Programming (With Examples)

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.
Syntax: 
      do{
            statement (s);
      } while(condition);

In do-while loop, the body of the loop is executed first without testing conditions. At the end of the loop, test condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is treu. When the condition becomes false, the loop is terminated, and the control gores to the statement that appears immediately after the while statement.

There is a minor difference between the working of while  and do-while loops. This difference is the place where the condition is tested. The while tests the condition before executing any of the statements withing the while loop. As against this, the do-while tests the condition after having executed the statements within the loop.

Example 1: Program to print the natural numbers from 1 to 100 using do-while loop. 

#include<stdio.h>
void main(){
 int n=1; 
 do{
  printf("%d \t",n); 
  n++; 
 }while(n<=100); 
 getch(); 
}
Output

Example 2: WAP to print the odd numbers from 1 to 10 using do-while loop
#include<stdio.h>
void main(){
 int n=1; 
 do{
  printf("%d \t",n); 
  n=n+2; 
 }while(n<=10); 
 getch(); 
}
Output
1      3      5      7      9

Example 3: WAP to print the multiplication table of given number using do-while loop
#include<stdio.h>
void main(){
 int n, i=1; 
 printf("Enter any Number : "); 
 scanf("%d",&n); 
 do{
  printf("%d x %d = %d\n", n, i, n*i);
  i++; 
 }while(i<=10);
 getch(); 
}
Output
Enter any Number : 12
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120

Example 4: WAP to ask the integer number n and calculate the sum of all natural numbers from 1 to n.
#include<stdio.h>
void main(){
 int n, sum=0; 
 printf("Enter any Number : "); 
 scanf("%d",&n); 
 do{
  sum=sum+n; 
  n--; 
 }while(n>=1);
 printf("The Sum is %d",sum); 
 getch(); 
}
Output
Enter any Number : 25
The Sum is 325

WAP to print the factorial of given number
#include<stdio.h>
void main(){
 int n, f=1; 
 printf("Enter any Number : "); 
 scanf("%d",&n); 
 do{
  f=f*n;
  n--; 
 }while(n>=1);
 printf("The Factorial is %d",f); 
 getch(); 
}
Output
Enter any Number : 10
The Factorial is 3628800

0 comments:

Post a Comment