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>
{ 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); 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 int add(int n); void main() { int m, x; printf("Enter an positive integer: "); scanf("%d",&m); x=add(m); printf("Sum = %d", x); getch();
int add(int n) { if(n!=0) return n+add(n-1); /* recursive call */ } |
No comments:
Post a Comment