#include <stdio.h>
int main() {
printf("\nNumber = %.2f", pow(2,3)); // Number = 4.00
printf("\nNumber = %.2f", pow(-2,3)); // Number = -8.00
printf("\nNumber = %.2f", pow(2,-3)); // Number = 0.12
printf("\nNumber = %.2f", pow(-2,-3)); // Number = -0.12
printf("\nNumber = %.2f", pow(0.2,4)); // Number = 0.00
return 0;
}
We will get first number to the power of second number ( x to the power of y ) by using pow()
function.
pow(x,y)
x, y = two input numbers .
#include <stdio.h>
#include <math.h>
int main(void){
int x,y,out;
x=2;
y=3;
out = pow(x,y);
printf("%d", out);
return 0;
}
The above code will give this output.
8
pow(num1,num2);
Output is here
16.977535
#include <stdio.h>
#include <math.h>
int main(void){
float x,y,out;
x=2.3;
y=-3.4;
out = pow(x,y);
printf("%f", out);
return 0;
}
0.058901
Enhance the tutorial by allowing users to input their base and exponent values.
#include <stdio.h>
#include <math.h>
int main() {
double base, exponent, result;
printf("Enter base: ");
scanf("%lf", &base);
printf("Enter exponent: ");
scanf("%lf", &exponent);
result = pow(base, exponent);
printf("%.2lf raised to the power of %.2lf is %.2lf\n", base, exponent, result);
return 0;
}
Output:
Enter base: 5
Enter exponent: 3
5.00 raised to the power of 3.00 is 125.00
Demonstrate how to handle negative exponents using pow().
#include <stdio.h>
#include <math.h>
int main() {
double base = 2, exponent = -3, result;
result = pow(base, exponent);
printf("%.2lf raised to the power of %.2lf is %.5lf\n", base, exponent, result);
return 0;
}
Output:
2.00 raised to the power of -3.00 is 0.12500
Using pow() to calculate roots (e.g., square roots, cube roots) by setting fractional exponents.
#include <stdio.h>
#include <math.h>
int main() {
double base = 27, exponent = 1.0/3.0, result;
result = pow(base, exponent);
printf("The cube root of %.2lf is %.2lf\n", base, result);
return 0;
}
Output:
The cube root of 27.00 is 3.00
Provide an alternative to pow() by implementing a custom power function using loops for integer exponents.
#include <stdio.h>
int power(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
int base = 3, exponent = 4;
int result = power(base, exponent);
printf("%d raised to the power of %d is %d\n", base, exponent, result);
return 0;
}
Output:
3 raised to the power of 4 is 81