Monday, January 5, 2015

C using Recursion program



Find the Nth Fibonacci Number using Recursion
 
#include 
#include 
int fibo(int);
int main()
{
    int num;
    int result;
    clrscr();
    printf("Enter the nth number in fibonacci series: ");
    scanf("%d", &num);
    if (num < 0)
    {
        printf("Fibonacci of negative number is not possible.\n");
    }
    else
    {
        result = fibo(num);
        printf("The %d number in fibonacci series is %d\n", num, result);
    }
    return 0;
}
int fibo(int num)
{
    if (num == 0)
    {
        return 0;
    }
    else if (num == 1)
    {
        return 1;
    }
    else
    {
        return(fibo(num - 1) + fibo(num - 2));
    } 
    getch();
}

Output
 
Enter the nth number in fibonacci series: 8
The 8 number in fibonacci series is 21
Enter the nth number in fibonacci series: 12
The 12 number in fibonacci series is 144
 
Find HCF of a given Number using Recursion
 
#include 
#include 
int hcf(int, int);
int main()
{
    int a, b, result;
    clrscr();
    printf("Enter the two numbers to find their HCF: ");
    scanf("%d%d", &a, &b);
    result = hcf(a, b);
    printf("The HCF of %d and %d is %d.\n", a, b, result);
}
int hcf(int a, int b)
{
    while (a != b)
    {
        if (a > b)
        {
            return hcf(a - b, b);
        }
        else
        {
            return hcf(a, b - a);
        }
    }
    return a;
    getch();
}
 
Output
 
Enter the two numbers to find their HCF: 24 36
The HCF of 24 and 36 is 12.
 
Find Power of a Number using Recursion
 
#include 
# include 
long power (int, int);
int main()
{
    int pow, num;
    long result;
    clrscr();
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Enter it's power: ");
    scanf("%d", &pow);
    result = power(num, pow);
    printf("%d^%d is %ld", num, pow, result);
    return 0;
}
long power (int num, int pow)
{
    if (pow)
    {
        return (num * power(num, pow - 1));
    }
    return 1;
}

Output
 
Enter a number: 456
Enter it's power: 3
456^3 is 94818816
 
Find the Factorial of a Number using Recursion
 
#include 
#include  
int factorial(int);
int main()
{
    int num;
    int result;
    clrscr();
    printf("Enter a number to find it's Factorial: ");
    scanf("%d", &num);
    if (num < 0)
    {
        printf("Factorial of negative number not possible\n");
    }
    else
    {
        result = factorial(num);
        printf("The Factorial of %d is %d.\n", num, result);
    }
    return 0;
}
int factorial(int num)
{
    if (num == 0 || num == 1)
    {
        return 1;
    }
    else
    {
        return(num * factorial(num - 1));
    }
}

Output
    
Enter a number to find it's Factorial: 6
The Factorial of 6 is 720.

No comments:

Post a Comment