How to calculate the power of a number in C++
In this shot, we will discuss how to calculate the power of a number. In other words, we will learn how to calculate the power of base to exponent.
Power of
basetoexponent=
For example, we have , which means 2 will be multiplied 3 times, which is 2 * 2 * 2. This gives an output of 8.
Solution
We will use a loop to calculate the power of a number. The loop will execute until the condition becomes false, after which the loop will be terminated. It will execute as many times as we give the value of the exponent.
To understand this better, let’s look at the code snippet below.
#include <iostream>using namespace std;int main() {int base, exponent, counter, result = 1;cin >> base >> exponent ;for (counter = 1; counter <= exponent ; counter++)result *= base;cout << "The power of a number is :" << result ;return 0;}
Enter the input below
Explanation
In order to pass the input to the code, you need to pass two numbers, the
baseand theexponent, in the above box, like so:4 5.
-
In line 6, we initialize the
base,exponent,countervariables andresult = 1. -
In line 7, we take the input as
baseandexponent. -
In lines 9 and 10, we run a loop and then multiply the
basewith itselfexponenttimes. -
In line 12, we print the result.
In this way, we can calculate the power of a number in C++ with loops.