C - do while loop in C programming example




👉Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again.
👉A do..while loop is almost the same as a while loop except that the loop body is guaranteed to execute at least once. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and then continue to loop while the condition is true".
👉Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). 
👉Notice that this loop will execute once, because it automatically executes before checking the condition.

Example 1 : -

#include<stdio.h>
#include<conio.h>
void main()
{
int a=5;
clrscr();
          do
          {
                   printf(" * ");
                   a++;
          }while(a<=20);
getch();
}

Output :-
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*


 For video tutorial you can see below video:-



Example 2 : -


#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter Number");
scanf("%d",&a);
          do
          {
                   printf("%d \n",a);
                   a=a+2;
          }while(a<=30);
getch();
}

Output :-
if user enter 2 then
2
4
6
8
.
.
.
30


Example 3 : -


 #include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter Number");
scanf("%d",&a);
          do
          {
                   printf("%d \n",a);
                   a--;
          }while(a>=-5);
getch();
}

Output :-
if user enters 5 then
5
4
3
2
1
0
-1
-2
-3
-4
-5

Example 4 : -


#include<stdio.h>
#include<conio.h>
void main()
{
          int i=1,n,sum=0;
          float avg;
          clrscr();
          printf("enter the no");
          scanf("%d",&n);
          do
          {
                   printf("%d \n",i);
                   sum=sum+i;
                   i++;
          }
          while(i<=n);
          printf("sum is %d\n",sum);
          avg=sum/n;
          printf("average is %f",avg);
          getch();
}

Output :-
if user enters 5 then
1
2
3
4
5
sum is 15
average is 3.0000


Example 5 : -


#include<stdio.h>
#include<conio.h>
void main()
{
          int a=1,n;
          clrscr();
          printf("enter no");
          scanf("%d",&n);
          do
          {
                   printf("%d \t %d \t %d \n",a,a*a,a*a*a);
                   a++;
          }
          while(a<=n);
          getch();
}

Output :-
if user enters 5 then
1    1    1
2    4    8
3    9    27
4    16  64
5    25  125

Post a Comment

0 Comments