4/4/08

Calculate power X^Y in C

A simple program in C programming language which asks from user to input two numbers (X,Y) and then calculates the result of X raised to the power of Y. Calculation is done with recursion and not and prints both results which of course must be the same! Maybe you want to see the code of MIPS power X^Y example.
Here is the code for the C power example:

#include <stdio.h>

/*
power recursive
return x^y
*/
int power(int x,int y){
if (y==0) return 1;
if (y==1) return x;
return( x*power(x,y-1) );
}
/*
power not recursive
return x^y
*/
int power2(int x,int y) {
if (y==0) return 1;
if (y==1) return x;

int result,i;
for (i=0,result=1;i<y;i++) {
result = result * x;
}
return(result);
}
int main() {
int x,y;
do{
printf("Give integer X from 1 to 20 : ");
scanf("%d",&x);
}
while( x>20 || x<1 );
do{
printf("Give integer Y from 0 to 5 : ");
scanf("%d",&y);
}
while( x>20 || x<1 );

printf("%d raised to %d gives %d \n",x,y,power(x,y));
printf("%d raised to %d gives %d ",x,y,power2(x,y));
exit (0);
}

The output is like that:

Please give integer X from 1 to 20: 2
Please give integer Y from 0 to 5: 5
X raised to Y gives: 32

You may want to see Simple MIPS counter or MIPS bubble sort.
Del.icio.us

1 comment:

pranali said...

plz tell us modification in an existing code if we want to calculate power of unsigned number and print result using shift operator

Related Posts Plugin for WordPress, Blogger...