Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts

Friday, November 2, 2012

program to find GCD using recursion

//also help to understand the command line argument

#include <stdio.h>
#include <stdlib.h>

int gcd(int, int);

int main(int argc, const char* argv[])       //command line argument
{
    int a, b;
    a = atoi(argv[1]);
    b = atoi(argv[2]);
   
    printf("The greatest commaon divisor of %d and %d is %d\n", a, b, gcd(a,b));
    return 0;
}

int gcd(int a, int b)
{
    if (b == 0)
        return a;                   //recursion implementation
    else
        return gcd(b, a % b);

}


 

Thursday, November 1, 2012

A simple program to understand recursion

#include <stdio.h>
#include <conio.h>

void recTest(int i)
{
    if(i > 0)
    {
        recTest(i - 1);          //understand this crazy little insane item
        printf("%i\n", i);
    }
}

int main()
{
    recTest(5);
}


OUTPUT:
1
2
3
4
5

Thursday, March 22, 2012

Program to find factorial using recursion in c

//1st way
#include <stdio.h>
#include <conio.h>

int fact(int);

int main()
{
    int num, f;
    printf ("\n Enter a number: ");
    scanf ("%d", &num);
    f = fact(num);
    printf (" \n Factorial of %d is: %d ", num, f);
}

int fact(int n)
{
    if(n == 1)
    {
        return 1;
    }
   
    else
    {
        return (n*fact(n-1));
    }

}

____________________________________________________________________
//2nd way
#include <stdio.h>
#include <conio.h>

int getFactorial(int n)
{
    int local;
    if (n > 1)
    {
        local = n * getFactorial(n-1);
        return local;
    }

    else
        return 1;
}

int main()
{
    int num, f;
    printf ( "\n Enter a number: " );
    scanf ("%d", &num);
    f = getFactorial(num);
    printf ( "\n Factorial of %d is: %d ", num, f);
}