Saturday, March 19, 2016

C Program to calculate x^y using recursive function.

/*=================================================================================
 **
 **  File Name     : powRecursion.c
 **  Creation Date : Sat 19 Mar 2016 06:02:15 AM IST
 **  Last Modified : Sat 19 Mar 2016 06:15:27 AM IST
 **  Compoler      : gcc
 **  Author        : Manoj Kumar Patra, manojpatra.sit@gmail.com
 **  Organization  : SCIS, University of Hyderabad, India.
 **
 **===============================================================================*/

#include<stdio.h>
long int power(int x, int y);
int i=1;
long int sum=1;
int main()
{
    printf("\n= = = = = Calculate power using recursive function = = = = =\n");
    int no, pow;
    long int result;
    printf("\nEnter a Number : ");
    scanf("%d",&no);
    printf("Enter the Power : ");
    scanf("%d",&pow);
    result = power(no,pow);
    printf("\n%d to the power %d is: %ld\n",no,pow,result);
    printf("\n\n= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\n");
}
long int power(int x, int pow)
{
    if(i<=pow)
    {
        sum=sum*x;
        power(x,pow-1);
    }
    else
        return sum;
}

OutPut:

max@ubuntu:~/cprog$ gcc powRecursion.c -o powRecursion
max@ubuntu:~/cprog$ ./powRecursion

= = = = = Calculate power using recursive function = = = = =

Enter a Number : 2
Enter the Power : 10

2 to the power 10 is: 1024


= = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

No comments:

Post a Comment