C Program to Reverse a Given Number
Program to Reverse a Number in C
In this post we will learn how to reverse a number in c. For example, if a user will enter 4567 as input then 7654 will be printed as output. This C program accepts an integer and reverse it.Working:-
For a user input num
- Initialize reverse = 0, rem
- Extract the last digit of num (rem = num % 10)
- Multiply reverse with 10 & add remainder (reverse = reverse * 10 + rem)
- Reduce the original number (num = num/10)
- Keep doing this until original number becomes 0
C program:-
#include<stdio.h> //main program int main () { //variables initialization int num, reverse = 0, rem; num=1234; printf("The number is: %d\n",num); //loop to find reverse number while(num != 0) { rem = num % 10; reverse = reverse * 10 + rem; num /= 10; }; //output printf("Reverse: %d\n",reverse); return 0; } // Time complexity O(N) // Space complexity : O(1)
Output:-
The number is: 1234 Reverse: 4321
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Method 2
This method uses a recursive approach.
Code
#include<stdio.h> int getReverse(int num, int rev){ if(num == 0) return rev; int rem = num % 10; rev = rev * 10 + rem; return getReverse(num / 10, rev); } //main program int main () { int num, rev = 0; num=1234; printf("The number is: %d\n",num); printf("Reverse: %d", getReverse(num, rev)); }
Output
The number is: 1234 Reverse: 4321
- Positive or Negative number: C | C++ | Java | Python
- Even or Odd number: C | C++ | Java | Python
- Sum of First N Natural numbers: C | C++ | Java | Python
- Sum of N natural numbers: C | C++ | Java | Python
- Sum of numbers in a given range: C | C++ | Java | Python
- Greatest of two numbers: C | C++ | Java | Python
- Greatest of the Three numbers: C | C++ | Java | Python
- Leap year or not: C | C++ | Java | Python
- Prime number: C | C++ | Java | Python
- Prime number within a given range: C | C++ | Java | Python
- Sum of digits of a number: C | C++ | Java | Python
- Reverse of a number : C | C++ | Java | Python
- Palindrome number: C | C++ | Java | Python
- Armstrong number : C | C++ | Java | Python
- Armstrong number in a given range : C | C++ | Java | Python
- Fibonacci Series upto nth term : C | C++ | Java | Python
- Find the Nth Term of the Fibonacci Series : C | C++ | Java | Python
- Factorial of a number : C | C++ | Java | Python
- Power of a number : C | C++ | Java | Python
- Factor of a number : C | C++ | Java | Python
- Strong number : C | C++ | Java | Python
- Perfect number : C | C++ | Java | Python
- Automorphic number : C | C++ | Java | Python
- Harshad number : C | C++ | Java | Python
- Abundant number : C| C++ | Java | Python
- Friendly pair : C | C++ | Java | Python
Program to sort given number in a array list
Hey there, thanks for commenting, Kindly join our Discord server for all the subject and technical queries.