Recursion

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 5

1

RETURN STATEMENT
The return statement terminates the execution of a function and returns a value to the calling
function. The program control is transferred to the calling function after return statement. In the
above example, the value of variable result is returned to the variable sum in the main() function.
2

Syntax of return statement


return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function
and the return type specified in function
prototype and function definition must match.
3

RECURSION IN C
When function is called within the same function, it is known as recursion in C. Any function
which calls itself is called recursive function, and such function calls are called recursive calls.
Let's see a simple example of recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}
The recursion continues until some condition is met to prevent it.

Example of recursion in C
Let's see an example to print factorial number using tail recursion in C language.

#include<stdio.h>
#include<conio.h>
int factorial (int n)
{
if ( n < 0)
return -1; /*Wrong value*/
if (n == 0)
return 1; /*Terminating condition*/
return (n * factorial (n -1));
}
void main()
{
int fact=0;
int n;
printf("\n Enter the value for n:");
scanf("%d",&n);
4

fact=factorial(n);
printf("\n Factorial of %d is %d",n,fact);
}
Output
Enter the value for n:5
Factorial of 5 is 120

Advantages and Disadvantages of Recursion


 Recursion makes program elegant and cleaner. All algorithms can be defined recursively
which makes it easier to visualize and prove.
 If the speed of the program is vital then, we should avoid using recursion. Recursions use
more memory and are generally slow. Instead, we can use loop.

Fibonacci Series using recursion(Another Example)

The following example generates the Fibonacci series for a given number using a recursive
function
#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
return 0;
else if (n == 1)
5

return 1;
else
return fibonacci(n-1)+fibonacci(n-2);

Reverse a sentence using recursion


#include <stdio.h>
void reverseSentence();
int main()
{
printf("Enter a sentence: ");
reverseSentence();
return 0;
}
void reverseSentence()
{
char c;
scanf("%c", &c);
if (c != '\n')
{
reverseSentence();
printf("%c", c);
}
}

You might also like