### GE6151 Computer Programming 4.3 Recursion in C:

4.3 Recursion in C:

Recursion is calling function by itself again and again until some specified condition has been satisfied.

Syntax:

int f_name (int x)

{

local variables;

f_name(y); // this is recursion statements;

}

Example_1: Factorial using Recursion

#include<stdio.h>

#include<conio.h> int factorial(int n); void main()

{

int res,x;

printf(“\n Enter the value:”); scanf(“%d”, &x); res=factorial(x);

printf(“The factorial of %d is ..%d”, res);

}

int factorial(int n)

{

int fact; if (n==1) return(1); else

fact = n*factorial(n-1);

return(fact); }

Example_2: Fibonacci using Recursion

#include<stdio.h>

#include<conio.h> int Fibonacci(int); int main()

{

int n, i = 0, c; scanf("%d",&n); printf("Fibonacci series\n"); for ( c = 1 ; c <= n ; c++ )

{

printf("%d\n", Fibonacci(i));

i++;

}

return 0;

}

int Fibonacci(int n)

{

if ( n == 0 )

return 0;

else if ( n == 1 )

return 1;

else

return ( Fibonacci(n-1) + Fibonacci(n-2) );

}

Example_3: Sum of n Natural Numbers

#include<stdio.h>

#include<conio.h>

void main()

{

int m, x;

printf("Enter an positive integer: ");

scanf("%d",&m);

printf("Sum = %d", x);

getch();

}