In my previous post, I had told about the implementation and working or while loop and today I am going to discuss the exit control do-while loop. I am giving you Do while loop example in which I’ll teach you how to print natural numbers in reverse order from 10 – 0.
In my previous post, I had already told how to print n natural numbers. Read that post because it will help you to understand today’s program. As well all know do while is an exit control loop which means it will execute once even if the condition is false and this will not happen in the other two loops.
Also read: Loops In C Language For, While and Do While
Program to print natural numbers in reverse order (10 – 0)
#include<stdio.h>
main()
{
int n = 10;
do
{
printf("%d ", n);
n--;
}while(n>=0);
}
Output: 10 9 8 7 6 5 4 3 2 1 0
Explanation of do while loop example
- In the braces of the main() function, I have started with int (integer data type) and declared one integer type variables n and initialized it by 10.
int n = 10;
- Declare the do-while loop and print the value of variable n after that use decrement operator to decrease the value of n by one unit.
- In last passed the condition that n must be greater or equal to zero.
do
{
printf("%d ", n);
n--;
}while(n>=0);
- Now when we run the program first it will print the value of n.
- Then it decreases its value by one unit (n–).
- Then checks the condition and if the condition is true then control goes to step one and all the steps execute until the condition becomes false.
Also read: C Program to Find the Sum of First Ten Natural Numbers using For Loop