Sunday, January 01, 2012

RECURSION

Introduction

A function calling itself is called Recursion. In some programs to fulfill a certain condition we use Recursion that is a function will call itself unit we get our desired result. A very simple example of it will be :

Addition of two numbers but the result should be an even number (Just add one with the second number if the result is an odd number) :

#include"stdio.h"
void cal (int, int);
main()
{
    int a, b;

    printf("Enter value for A : ");
    scanf("%d",&a);

    printf("Enter value for B : ");
    scanf("%d",&b);

    cal(a,b);
}

void cal (int a, int b)
{
    int c;
        if((a+b)%2==0)
        {
            c=a+b;
            printf("A + B = %d  \n",c);
        }
        else
        {
            printf("(Added 1 with the Second Number)  \n");

            cal(a,b+1);  // Called Itself
        }
}

It will Count Its Own Call :

#include"stdio.h"
#include"stdlib.h"  //  exit() is defined under stdlib.h.
void fun (int);
void main()
{
    int counter=0;

    fun(counter);
}

void fun (int counter)
{
    if (counter==100)
    {
        exit(0);  // This function will take an exit from the total program.
    }
        counter++;

        printf("%d Called itself 100 Times \n",counter);

        fun(counter);
}

Binary Conversion :

#include"stdio.h"
void bin(int);
void main()
{
    int n;
    printf("Enter a Number : ");
    scanf("%d",&n);

    printf("\nNumber = %d \t Binary = ",n);

    bin(n);

    printf("\n\n");
}

void bin(int n)
{   
    if(n>1)
        bin(n/2);

    printf("%d",n%2);
}

Binary Conversion ( 0 - 100 ) :

#include"stdio.h"
void bin(int);
void main()
{
    printf("Decimal \t Binary\n");
    printf("__________________________\n");

    for(int i=0;i<=100;i++)
    {
        printf("\n%d -------------- ",i);
        bin(i);
        printf("\n");
    }
    printf("\n\n");
}

void bin(int i)
{   
    if(i>1)
        bin(i/2);

    printf("%d",i%2);
}

Will Work Like an Odd Loop :

#include"stdio.h"
void neg(int);
main()
{
    int i=0;
    neg(i);
}

void neg(int i)
{
    static int f=0;

    if(i>=0)
    {
        printf("To Exit from this Function a Negative Number has to be Entered : ");
        scanf("%d",&i);

        if(i>=1)
            f=f+i;

        neg(i);
    }
    else
    {   
        printf("Sum of all Positive Numbers You Entered is %d \n",f);
    }
}

No comments:

Post a Comment

Followers