C Power Function
[Legacy Content] This page contains very old information, which might not be valid anymore, they are only kept here for legacy purposes.
if you have any inquiries, feel free to contact me! Click here
C Power Function
Created: Tuesday, 22 October 2013 Written by Ehab Eldeeb
Write a C Function that calculates X Power Y
double power(double base, int pow){
double result = 1;
for (int i = 1; i <= pow; i++)
result *= base;
return result;
}
Write the same function using recursion
double power (double base, int pow){
if (pow==1)
return base * 1;
else if (pow > 0)
pow--;
return base * (power(base,pow));
}
Using the function in the main program
#include <stdio.h>
#include <conio.h>
int main(){
double x, result;
int y;
printf("Enter Base: ");
scanf("%lf", &x);
printf("Enter Power: ");
scanf("%d", &y);
result = power(x,y); // Here we used the function to calculate the X power Y
printf("%lf Power %d = %lf", x, y, result);
getch();
return 0;
}