C Program To Find Reverses Of Given Number
Table of contents
#include <stdio.h>
int main() {
int n, reverse = 0;
printf("Enter an integer: ");
scanf("%d", &n);
while(n>0) {
reverse = reverse*10 + n%10;
n /= 10;
}
printf("Reversed number = %d", reverse);
return 0;
}
This program uses a single while loop and eliminates the extra variable remainder
. The program works the same way as the previous one. The user is prompted to enter an integer, which is stored in the variable n
. The while loop continues as long as n
is greater than 0. In each iteration, the reverse variable is updated by adding the last digit of n obtained by n%10
and multiply it by 10. Finally, n is updated by dividing it by 10, which removes the last digit. After the while loop, the reversed number is printed.
EXPLANATION :
The program prompts the user to enter an integer: "Enter an integer: "
The user enters the integer 12345
The program begins executing the while loop:
In the first iteration, the value of
n
is 12345. The value ofreverse
is updated to bereverse * 10 + n % 10
which is 0 * 10 + 12345 % 10 = 5. The value ofn
is updated to ben / 10
which is 12345 / 10 = 1234.In the second iteration, the value of
n
is 1234. The value ofreverse
is updated to bereverse * 10 + n % 10
which is 5 * 10 + 1234 % 10 = 54. The value ofn
is updated to ben / 10
which is 1234 / 10 = 123.In the third iteration, the value of
n
is 123. The value ofreverse
is updated to bereverse * 10 + n % 10
which is 54 * 10 + 123 % 10 = 543. The value ofn
is updated to ben / 10
which is 123 / 10 = 12.In the fourth iteration, the value of
n
is 12. The value ofreverse
is updated to bereverse * 10 + n % 10
which is 543 * 10 + 12 % 10 = 5432. The value ofn
is updated to ben / 10
which is 12 / 10 = 1.In the fifth iteration, the value of
n
is 1. The value ofreverse
is updated to bereverse * 10 + n % 10
which is 5432 * 10 + 1 % 10 = 54321. The value ofn
is updated to ben / 10
which is 1 / 10 = 0.Since the value of
n
is 0, the condition of the while loop is no longer true and the loop exits.
The program prints the final value of
reverse
which is 54321: "Reversed number = 54321"
So the output will be "Reversed number = 54321"
Note that the input can be any integer, The output will be the reversed version of the input number.
Subscribe to my newsletter
Read articles from Stark Engineering directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Stark Engineering
Stark Engineering
"Stark Engineering is a one-stop destination for all your engineering needs. From cutting-edge technology to expert insights, our website is dedicated to providing the latest information and resources to help you stay ahead in the field of engineering. Whether you're a student, professional, or enthusiast, we are committed to delivering high-quality content that will help you learn, grow, and excel in your field. Explore the world of engineering with Stark Engineering and unlock the full potential of your passion."