Write a C program to find reverse a number using recursion.
#include <stdio.h>
/* finds the reverse of val and store it in res */
int reverseNum(int val, int *res) {
int rem;
/* reverse of the given number manipulation */
if (val) {
rem = val % 10;
*res = (*res * 10) + rem;
reverseNum(val/10, res);
}
return;
}
int main() {
int val, res = 0;
/* get the input from the user */
printf("Enter your input value:");
scanf("%d", &val);
printf("Reverse of %d is ", val);
/* finds the reverse of the given number */
reverseNum(val, &res);
/* prints the result */
printf("%d\n", res);
return 0;
}
/* finds the reverse of val and store it in res */
int reverseNum(int val, int *res) {
int rem;
/* reverse of the given number manipulation */
if (val) {
rem = val % 10;
*res = (*res * 10) + rem;
reverseNum(val/10, res);
}
return;
}
int main() {
int val, res = 0;
/* get the input from the user */
printf("Enter your input value:");
scanf("%d", &val);
printf("Reverse of %d is ", val);
/* finds the reverse of the given number */
reverseNum(val, &res);
/* prints the result */
printf("%d\n", res);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input value:12345
Reverse of 12345 is 54321
Enter your input value:12345
Reverse of 12345 is 54321
No comments:
Post a Comment