What is Power Function in C Library?

What is the Power Function in C?

The power function in C is used to raise a number (called the base) to the power of another number (called the exponent). In simple terms, it computes:

pow(base, exponent) = base ^ exponent

For example:

pow(2, 3) = 2 × 2 × 2 = 8

Syntax of pow() Function

To use the pow() function, include the math.h header file in your program:​

#include <math.h>

The function prototype is:​

advertisement
double pow(double base, double exponent);
  • base – the number to be raised.
  • exponent – the power to which the base is raised.

Example of Power Function in C

#include <stdio.h>
#include <math.h>
 
int main() {
    double quizMarks = 3.0;
    double attempts = 4.0;
 
    double totalScore = pow(quizMarks, attempts); // 3^4 = 81
 
    printf("C Programming Score: %.2f\n", totalScore);
    return 0;
}

Output:

C Programming Score: 81.00

This C program calculates a score using the pow() function from the library. It sets quizMarks to 3.0 and attempts to 4.0. Using pow(quizMarks, attempts), it calculates 3 raised to the power of 4, which gives 81. The result is stored in totalScore and printed with two decimal places. This simple example shows how to use power functions for mathematical tasks in C.

Important Notes:

  • Always include math.h or you’ll get an “implicit declaration” warning.
  • Compile with -lm if using GCC:
  • gcc program.c -o program -lm
  • Return value is of type double, so you may need to cast it if you want an integer.
  • int result = (int)pow(2, 3);  // result = 8
  • If you pass a negative base with a non-integer exponent, the result is undefined (NaN).

pow() Function with Different Data Types

Although pow() accepts and returns double, you can use it with integers by typecasting:

int base = 5, exp = 2;
int result = (int)pow((double)base, (double)exp);  // result = 25

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.