- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain recursive function in C language with program
Recursive Functions is the process of defining something in terms of itself. It is a function that calls itself again in the body of the function.
A function fact ( ), that computes the factorial of an integer ‘N’ ,which is the product of all whole numbers from 1 to N.
When fact ( ) is called with an argument of 1 (or) 0, the function returns 1. Otherwise, it returns the product of 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 recursive function −
#include<stdio.h> int main ( ){ int n,f; int fact (int); 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
When the above program is executed, it produces the following result −
Enter a number 5 Factorial value = 120
Advertisements