Write a C++ Program to Calculate Power of a Number

Calculating the power of a number is a fundamental mathematical operation that is commonly required in many programming applications.

In C++, you can use the pow() function from the cmath library to calculate the power of a number.

However, it is also possible to calculate the power of a number using a simple loop.

Here’s a simple C++ program that calculates the power of a number using a loop:

#include <iostream>
using namespace std;

int main()
{
    double base, exponent, result = 1;
    cout << "Enter base and exponent respectively: ";
    cin >> base >> exponent;

    for(int i = 1; i <= exponent; i++)
    {
        result *= base;
    }

    cout << base << "^" << exponent << " = " << result;

    return 0;
}

In the above program, we first declare three variables: base, exponent, and result. The result variable is initialized to 1 since any number raised to the power of 0 is 1.

Next, we prompt the user to enter the base and exponent values using the cin object.

We then use a for loop to calculate the power of the number. Inside the loop, we multiply the result variable by the base value in each iteration.

The loop continues until the value of i reaches the value of exponent.

Finally, we output the result using the cout object.

You can use this code as a starting point to create more complex power calculation functions that take into account special cases such as negative exponents or fractional exponents.

But for simple integer exponents, the above code should suffice.

I hope this has been helpful in demonstrating how to calculate the power of a number in C++.