Recursion in C Programming

Introduction

When a function calls itself within itself it is known as recursion in C programming. In this article, we are going to discuss recursion in c and will see one example of recursion.

Getting Started

When a function calls itself within itself it is known as recursion, any function in a C program can be called recursively; that is, it can call itself.

The number of recursive calls is limited to the size of the stack. Each time the function is called, new storage is allocated for the parameters and for the auto and register variables so that their values in previous, unfinished calls are not overwritten. Parameters are only directly accessible to the instance of the function in which they are created. Previous parameters are not directly accessible to ensuing instances of the function.

A function that has to be called recursively must be declared not-void type. If a function is declared as void, then it can’t be defined as a recursive function.

Note that variables declared with static storage do not require new storage with each recursive call. Their storage exists for the lifetime of the program. Each reference to such a variable accesses the same storage area.

Recursion Examples

This example illustrates recursive calls: Where it accept a number and displays it factorials.

 # include <stdio.h>  
 # include <conio.h>  
 int factorial( int num );/* Function prototype */  
 int main()  
 {  
      int result, number;  
      chrscr();  
      printf("\n Enter a number whose factorial you want.");  
      scanf("%d", & number);  
      printf("\n Factorial of %d=%d", number, factorial(number));  
      getch();  
 }  
 int factorial( int num )   /* Function definition */  
 {  
   if (num ==0)  
           return (1);  
      else  
     return( num * factorial( num - 1 ) );  
 }  

Summary

Thanks

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال