Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Calculate Power of a Number in C++

Use pow(base, exponent) from <cmath> to raise numbers to any power in C++, including fractional and negative exponents. Covers NaN, inf, and rounding.

BeginnerAdvanced Number ProgramsExample 2 of 13
calculate-power-of-a-number.cpp
1#include <iostream>
2#include <cmath>
3using namespace std;
4
5int main() {
6 double base, exponent;
7
8 cout << "Enter base: ";
9 cin >> base;
10
11 cout << "Enter exponent: ";
12 cin >> exponent;
13
14 // Method 1: Using pow() function
15 double result = pow(base, exponent);
16
17 cout << base << " raised to the power " << exponent << " = " << result << endl;
18
19 return 0;
20}

Sample Output

2 raised to the power 8 = 256

pow result printed in default format.

In this one

  • How pow handles whole, fractional, and negative exponents
  • When pow returns nan or inf
  • Why integer results from pow can be off by rounding
  • How a fast exponentiation loop avoids pow for integers

How it works

  1. 1

    Read base (2) and exponent (8).

  2. 2

    pow(2, 8) returns 256.0.

  3. 3

    cout prints 256 without a decimal part.

Edge cases

Huge result

Enter 10 and 400.

The value exceeds the largest double, so pow returns inf and cout prints inf.

Casting a pow result to int

int r = pow(5, 2);

On most systems this is 25, but floating point can return 24.999999 on some libraries and truncation gives 24. Use round or an integer loop.

What's going on

This listing is the pow lesson seen from the advanced side: the call itself is one line, so the interesting part is what pow does with fractions, negatives, and very large results.

This C++ program computes base^exponent with pow from <cmath>. 2^8 is 256.

#include <cmath>

Skip it and pow is an unknown name.

double base, exponent, result;

double so 2.5 and -2 still work. int would truncate 2^(-3).

result = pow(base, exponent);

^ is XOR. 2 ^ 8 is 10, not 256. Don't.

Special cases pow already handles: anything^0 is 1, 2^1 is 2. Fractional exponent 4^0.5 is 2. Negative exponent 2^-3 is 0.125.

A loop result *= base n times only works for a non-negative integer exponent. That's why the library function exists.

Sample: 2 raised to the power 8 = 256.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

pow(2, -2) returns:

Pick an answer to check it.

Question 2

Which expression squares x without pow?

Pick an answer to check it.

Questions people ask

What is 0 to the power 0?

pow(0, 0) returns 1, by convention.

How do I compute an integer power exactly?

Multiply in a loop, or use exponentiation by squaring, both in integer types.

Is pow slow?

It is a general floating-point function. For squaring, x * x is simpler and exact.