C program to find the reverse of a number has been shown here. For example, if a number is 12345 then the reverse of the number is 54321. The following section covers both of the iterative and recursive approaches to find the reverse of a number. The algorithm, pseudocode and time complexity of the program have been shown below.
Page content(s):
1. Algorithm to find reverse of a number
1. Take a number n as input.
2. Initialize a variable to 0 say reverse = 0.
3. Perform r = n % 10.
4. Perform reverse = reverse * 10 + r.
5. Perform n = n / 10
6. If n = 0 stop the process and display reverse as output else go to step 3.
2. Pseudocode to find reverse of a number
Input : A number $n$
Output : The reverse of the number $n$
1. Procedure reverse($n$):
2.
3.
4.
5.
6.
7. End Procedure
3. Time complexity to find reverse of a number
Time Complexity: O(log(n))
Where n is the input number.
4. Program & output to find reverse of a number
4.1. C Program & output to find reverse of a number using iteration
/***************************** alphabetacoder.com C program to find the reverse of a number using iteration ******************************/ #include <stdio.h> int main() { // declare variables int num, revnum = 0, r; // take input of the number printf("Enter the number = "); scanf("%d", & num); //find the reverse while (num != 0) { // extract the unit digit r = num % 10; // store the reverse number. // provide appropriate positional value // of each digit in each iteration. revnum = revnum * 10 + r; //divide the number by 10 num = num / 10; } // display result printf("Reverse of the number = %d", revnum); return 0; }
Output
Case 1:
Enter the number = 12345
Reverse of the number = 54321
Case 2:
Enter the number = 8421
Reverse of the number = 1248
4.2. C Program & output to find reverse of a number using recursion
/***************************** alphabetacoder.com C program to find the reverse of a number using recursion ******************************/ #include <stdio.h> // recursive function to reverse a number int reverse(int num, int rev) { if (num == 0) return rev; else return reverse(num / 10, (rev * 10 + num % 10)); } int main() { // declare variables int num; // take input of the number printf("Enter the number = "); scanf("%d", & num); //find the reverse by calling function // The function has two parameters. // First one is the number and second one // is for storing the reverse of a number // display the result printf("Reverse of the number = %d", reverse(num, 0)); return 0; }
Output
Case 1:
Enter the number = 6345
Reverse of the number = 5436
Case 2:
Enter the number = 5
Reverse of the number = 5