Power of a number

The power of a number represents the number of times to use that number in a multiplication. Usually, power is represented with a base number and an exponent.

Logic

Let’s declare one temporary variable power with value 1, we have used the data-type long long so that it can hold a big long value.

To calculate the power of a number we need a base and an exponent value, we are taking these two values from the user, after taking input (base, exponent) from the user we start one loop from 1 to exponent.

Inside the loop, for every iteration, we multiply the base by power (base * power) and store the result again in variable power until the loop is completed.

Once the loop is over, simply print the variable power containing the resultant power value of a given number.

Program

#include <iostream>

using namespace std;

int main() {

    int base, exponent;
    long long power = 1;
    int i;
    
    // Take input from user
    cout << "Enter base and exponent : ";
    cin >> base >> exponent;

    // Multiply base, exponent times
    for(i = 1; i <= exponent; i++) {
        power = power * base;
    }

    cout << endl << "Result " << base << " ^ " << exponent << " : " << power;

    return 0;
}

Output

Enter base and exponent : 2 5
Result : 2 ^ 5 = 32