Recursive program to reverse a number
Recursive program to reverse a number
Given a number , write a Recursive program to reverse a number .
Sample input:-
253
Sample output:-
Reverse of 253 is 352
Recursive program to reverse a number:-
The objective of this code is to reverse the number .
Method 1:-
In this method we will create a function ReverseNumber() in which we will pass two parameter first for number and second for the Reverse number . In second parameter we will store the final and i.e reverse of the number . And the base case for this function is if n==0 the return second parameter.
C Code:-
#include<stdio.h> // recursive function to reverse the number int ReverseNumber(int n, int reverse) { if(n==0) return reverse; else { int r=n%10; n=n/10; reverse=reverse*10+r; return ReverseNumber(n,reverse); } } // Driver function int main() { int n; printf("Enter a number\n"); scanf("%d",&n); printf("Reverse of %d is %d ",n,ReverseNumber(n,0)); return 0; }
Output:-
Enter a number 256 Reverse of 256 is 652
Method 2:-
In this method instead of using the second parameter we will use a global variable Rev_num for storing the reverse of the number.
#include<stdio.h> int Rev_num=0; // recursive function to reverse the number void ReverseNumber(int n) { if(n) { int r=n%10; Rev_num=Rev_num*10+r; n=n/10; ReverseNumber(n); } } // Driver function int main() { int n; printf("Enter a number\n"); scanf("%d",&n); ReverseNumber(n); printf("Reverse of %d is %d ",n,Rev_num); return 0; }
Output:-
Enter a number 256 Reverse of 256 is 652
Recommended post:-
codechef problems:-
- Primary test
- Sum or difference
- point and line
Wipro :-
- Update the booking ID | Wipro previous year question paper solution
- Pages in PDF
- Find the location id
- Find the odd digits
- Find the Product ID
Infytq :-
Key Points;-
Hackerrank:-
- Python : missing characters : hackerrank solution
- Python : string transformation | Hackerrank solution
- Active Traders certification test problem | Hackerrank Solution
- Usernames changes certification test problem | Hackerrank Solution
- string Representation of objects certification test hackerrank solution
- Average Function | hackerrank certification problem solution
C-tutorial:-
- Micros in C
- Pointer in c
- Function declaration
- Types of user define function
- return type of function
- 2D array
See more:-
- c program to convert specified days into years weeks and days
- Print Reverse Hollow Pyramid
- Update the booking ID | Wipro previous year question paper
- Pages in PDF | Wipro previous year question paper
- Sparse Matrix in data structure
- Find the location ID | Wipro previous year Coding question
- find the odd digits | Wipro Coding question
- Find the product id | Wipro Coding question
- Difference between static and dynamic memory allocation
- What is asymptotic Notation