In this tutorial, you will learn how to write a C program to print all natural numbers in reverse order using a while loop conditional statement. We will explore examples and algorithms with explanations for your better understanding of this problem.
Required Knowledge
- C Programming Basics
- C Programming Operators
- C printf and Scanf
- While loop in C
Problem Statement
You have to Write a C Program that prints all natural numbers in reverse order using a while loop. The program provides a solution to print natural numbers in reverse order using a while loop in the C programming language. For a better understanding, you can see the below example. It will help you to understand what exactly you have to achieve.
Example
Output:
10
9
8
7
6
5
4
3
2
1
Here the input is not given by the user. We have kept the hardcoded value 10 and printed them in reverse order.
Algorithm
- Start the program.
- Declare the variable
num
to store the current number. - Initialize
num
to 10. - Enter the while loop with the condition
num >= 1
.- Print the value of
num
. - Decrement
num
by 1.
- Print the value of
- Exit the while loop.
- End the program.
Logic used to solve this problem
- Declare a variable to hold the maximum limit of the natural numbers.
- Prompt the user to enter the maximum limit.
- Read and store the entered maximum limit in the variable.
- Initialize a counter variable with the maximum limit.
- Use a while loop that runs as long as the counter is greater than or equal to 1.
- Inside the loop, print the value of the counter.
- Decrement the counter by 1 in each iteration.
- Continue the loop until the counter becomes less than 1.
- Finish the program.
Program to Print all Natural numbers in Reverse Order
#include <stdio.h>
int main() {
int num = 10;
while (num >= 1) {
printf("%d\n", num);
num--;
}
return 0;
}
Output
10
9
8
7
6
5
4
3
2
1
Program Explanation
- The program takes input for the value of n from the user.
- It initializes a variable
num
to n, which represents the starting point for printing the numbers. - The program enters a while loop with the condition
num >= 1
to iterate through numbers from n to 1. - Inside the while loop, it prints the value of
num
on the screen. - It then decrements the value of
num
by 1 to move on to the next number in reverse order. - The loop continues until
num
reaches 1. - Once the while loop is complete, the program ends.
Conclusion
The C program successfully prints all natural numbers in reverse order using a while loop. By starting with an initial value and decrementing it in each iteration, the program displays the numbers in descending order on the screen.