Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C Program to reverse a given number using Recursive function
"Recursive function" is something which calls itself again in the body of the function.
For example,
A function fact ( ), which computes the factorial of an integer ‘N’, which is the product of all whole numbers from 1 to N.
fact ( ) with an argument of 1 (or) 0, the function returns 1. otherwise, it returns n*fact (n-1), this happens until ‘n’ equals 1.
Fact (5) =5* fact (4) =5*4*3* fact (3) =5*4*3*2* fact (2) =5*4*3*2*1 fact (1) =5*4*3*2*1 = 120.
Example
Following is the C program for use of recursive function to reverse a number −
#include<stdio.h>
main ( ){
int n,f;
int fact (int);
clrscr ( );
printf ("enter a number");
scanf ("%d", &n);
f= fact (n);
printf (factorial value = %d",f);
}
int fact (int n){
int f;
if ( ( n==1) || (n==0))
return 1;
else
f= n*fact (n-1);
return f;
}
Output
The output is given below −
Enter a number 5 Factorial value = 120
Given below is another C Program to reverse a given number using Recursive function −
#include<stdio.h>
int sum=0,rem;
int main(){
int num,revNum;
printf("enter number:
");
scanf("%d",&num);
revNum=revNumFunction(num);//calling function to reverse the given number
printf("the number after reverse :%d",revNum);
return 0;
}
revNumFunction(int num){
if(num){
rem=num%10;
sum=sum*10+rem;
revNum(num/10);
}
else
return sum;
}
Output
The output is as follows −
enter number: 1357 the number after reverse is :7531
Advertisements