Here are a few examples of the do-while loop.
Printing table of a number using do-while:
#include<stdio.h>
int main(){
int i=1;
do{
printf("6 * %d = %d \n",i,i*6);
i++;
}while(i<=10);
return 0;
}
output:
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
6 * 6 = 36
6 * 7 = 42
6 * 8 = 48
6 * 9 = 54
6 * 10 = 60
- using the do-while loop, the value of ‘i’ is multiplied by 6.
- The loop continues till the value of ‘i’ is less than or equal to 10.
- Finally, the table of the given number is printed.
Calculating factorial of a number using a do-while loop:
#include<stdio.h>
void main()
{
int n,i=1,f=1;
printf("\n Enter The Number:");
scanf("%d",&n);
//LOOP TO CALCULATE THE FACTORIAL OF A NUMBER
do
{
f=f*i;
i++;
}while(i<=n);
printf("\n The Factorial of %d is %d",n,f);
}
output:
Enter The Number:5
The Factorial of 5 is 120
- first, the computer reads the number to find the factorial of the number from the user.
- Then, using the do-while loop, the value of ‘i’ is multiplied by the value of ‘f’.
- The loop continues till the value of ‘i’ is less than or equal to ‘n’.
- Finally, the factorial value of the given number is printed.
printing reverse of a number:
#include<stdio.h>
void main()
{
int num,reverse=0,rem;
printf("Enter a number: ");
scanf("%d",&num);
do{
rem=num%10;
reverse=reverse*10+rem;
num/=10;
}while(num!=0);
printf("Reverse number %d\n",reverse);
}
output:
Enter a number: 12345
Reverse number 54321
- first, the computer reads the number to find the reverse of the number from the user.
- Then, using the do-while loop, the digit of the number is extracted and added in the ‘reverse’.
- The loop continues till the value of ‘num’ is not equal to 0.
- Finally, the reverse value of the given number is printed.
In the above-given do-while loop examples, we could clearly see that it is an exit-controlled loop.
Note: also read about do-while loop in c & while loop examples in c
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment