C library - pow() function



The C library pow() function of type double accepts the parameter x and y that simplifies the x raised to the power of y.

This function allows programmers to calculate a base number raised to a specified exponent without the usage of implementing complex multiplication loops manually.

Syntax

Following is the syntax of the C library function pow()

double pow(double x, double y)

Parameters

This function accepts only two parameter −

  • x − This is the floating point base value.

  • y − This is the floating point power value.

Return Value

This function returns the result of raising x to the power y.

Example 1

Following is the basic C program that demonstrates the usage of pow() function.

#include <stdio.h>
#include <math.h>

int main () {
   printf("Value 8.0 ^ 3 = %lf\n", pow(8.0, 3));

   printf("Value 3.05 ^ 1.98 = %lf", pow(3.05, 1.98));
   
   return(0);
}

Output

The above code produces the following result −

Value 8.0 ^ 3 = 512.000000
Value 3.05 ^ 1.98 = 9.097324

Example 2

In the below program, we illustrate the table of power for a given base using pow().

#include <stdio.h>
#include <math.h>

int main() {
   double base;
   printf("Enter the base number: ");
   scanf("%lf", &base);

   printf("Powers of %.2lf:\n", base);
   for (int i = 0; i <= 10; ++i) {
       double result = pow(base, i);
       printf("%.2lf ^ %d = %.2lf\n", base, i, result);
   }

   return 0;
}

Output

On execution of above code, we get the following result −

Enter the base number: 5
Powers of 5.00:
5.00 ^ 0 = 1.00
5.00 ^ 1 = 5.00
5.00 ^ 2 = 25.00
5.00 ^ 3 = 125.00
5.00 ^ 4 = 625.00
5.00 ^ 5 = 3125.00
5.00 ^ 6 = 15625.00
5.00 ^ 7 = 78125.00
5.00 ^ 8 = 390625.00
5.00 ^ 9 = 1953125.00
5.00 ^ 10 = 9765625.00

Example 3

Here, we create a program that accepts user input for the base and exponent and calculates the result using pow(), and show the result.

#include <stdio.h>
#include <math.h>

int main() {
   double base, exponent, result;
   printf("Enter the base number: ");
   scanf("%lf", &base);
   printf("Enter the exponent: ");
   scanf("%lf", &exponent);

   result = pow(base, exponent);
   printf("%.2lf ^ %.2lf = %.2lf\n", base, exponent, result);

   return 0;
}

Output

After executing the code, we get the following result −

Enter the base number: 5
Enter the exponent: 2
5.00 ^ 2.00 = 25.00

Or,

Enter the base number: 3
Enter the exponent: 3
3.00 ^ 3.00 = 27.00
Advertisements