Course contentsShow
← C
Lesson 861 of 1,21912. The Standard LibraryFree lesson

Basic power and square root: `pow` and `sqrt`

Basic power and square root: pow and sqrt

What you'll learn: How to perform common exponent and square root calculations using the standard C math library.

In basic C arithmetic, we have operators for addition (+), subtraction (-), and even remainder (%). However, there is no "exponent" operator (like ^ in some languages) to calculate powers. To handle these operations, C provides a dedicated toolkit via the <math.h> header file.

The pow() function

Think of pow() as a shortcut for repeated multiplication. If you want to calculate "5 to the power of 3" (5 * 5 * 5), you use pow(base, exponent).

A crucial detail to remember is that pow() works with doubles (floating-point numbers). Even if you pass in integers, the function will treat them as decimals and return a decimal result. This is necessary because math gets messy quickly—imagine calculating 2 to the power of 0.5!

The sqrt() function

The sqrt() function is the inverse of a square. It asks the question: "What number, multiplied by itself, gives me this value?" For example, sqrt(16.0) will return 4.0. Like its sibling pow(), it expects a double and returns a double.

One golden rule: you cannot take the square root of a negative number in standard real-number math. If you try to pass a negative value to sqrt(), your program might return "NaN" (Not a Number).

Seeing it in action

To use these functions, you must include the math library at the very top of your file.

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

int main() {
    double base = 5.0;
    double exponent = 2.0;
    
    // Calculating 5 squared (5^2)
    double power_result = pow(base, exponent);
    printf("5 to the power of 2 is %.1f\n", power_result);
    
    // Calculating the square root of 64
    double root_result = sqrt(64.0);
    printf("The square root of 64 is %.1f\n", root_result);

    return 0;
}

Compilation Tip

On some systems (like Linux), when you use <math.h>, you need to tell the compiler to link the math library manually by adding -lm to the end of your compile command, like this: gcc main.c -lm.

Key takeaway

Use pow(x, y) for exponents and sqrt(x) for square roots, ensuring you include <math.h> and use double data types for precision.