In this C program, we will calculate the power of a number using the exponentiation operator. We will take the base value ‘x’ and the exponent value ‘n’ from the user, and then calculate the result of x raised to the power of n.
Problem statement
Write a C program to calculate the power of a number using the exponentiation operator.
C Program to Calculate Pow (x,n)
#include<stdio.h>
#include<math.h>
double calculatePower(double x, int n);
int main()
{
double x;
int n;
double result;
printf("Enter the base value (x): ");
scanf("%lf", &x);
printf("Enter the exponent value (n): ");
scanf("%d", &n);
result = calculatePower(x, n);
printf("Result: %.2lf\n", result);
return 0;
}
double calculatePower(double x, int n)
{
return pow(x, n);
}How it works
- We include the necessary header files
stdio.handmath.h. Thestdio.hheader file provides input/output functions, and themath.hheader file provides mathematical functions such aspow. - We declare a function
calculatePowerthat takes a double valuexas the base and an integer valuenas the exponent. This function uses thepowfunction frommath.hto calculate and return the result of x raised to the power of n. - In the
mainfunction, we declare variablesx,n, andresult. - We prompt the user to enter the base value (x) and read it using
scanfwith the%lfformat specifier for a double. - We prompt the user to enter the exponent value (n) and read it using
scanfwith the%dformat specifier for an integer. - We call the
calculatePowerfunction, passingxandnas arguments, and assign the returned value to theresultvariable. - Finally, we display the result using
printfwith the%.2lfformat specifier to display the result with two decimal places.
Input / Output
