Thursday, July 14, 2011

Functions: RECURSIVE FUNCTION

RECURSIVE FUNCTION
Recursion in computer programming defines a function in terms of itself. One example application of recursion is in recursive descent parsers for programming languages. The great advantage of recursion is that an infinite set of possible sentences, designs, or other data can be defined, parsed, or produced by a finite computer program.
syntax:
void function()
{
   .. .. ..
   .. .. ..
   function();
   .. .. ..
   .. .. ..
}
Example 1: Write a program to find out the factorial of nth term using recursive function.
#include<stdio.h>
#include<conio.h>
 
long int fact(int n)
{
    long int f;
   
    if(n==1)
          return(1)
    else
          f = n * fact(n-1);
 
    return(f);
}
 
main()
{
    long int f;
    int x;
 
    printf("enter the value for x:")
    scanf("%d", &x);
 
    f = fact(x);
 
    printf(" Factorial of x is %ld", f);
    getch();
}

Example 2: Write a program to find out the sum of digit of an integer number using recursive function.
#include<stdio.h>
#include<conio.h>
 
int sumdigit(int n)
{
    int sum;
   
    if(n<10)
          return(n)
    else
          sum = (n%10) * sumdigit(n/10);
 
    return(sum);
}
main()
{
    int sum;
    int x;
 
    printf("enter the value for x:")
    scanf("%d", &x);
 
    sum = fact(x);
 
    printf(" sum of digit is %d", sum);
    getch();
}

0 comments:

Post a Comment