Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
power
communitycreator

How to calculate the power of a number in C++

Vinisha Maheshwari

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 base to exponent = baseexponentbase^{exponent}

For example, we have 232^{3}, 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

Calculate the power of base to the exponent in C++

Explanation

In order to pass the input to the code, you need to pass two numbers, the base and the exponent, in the above box, like so: 4 5.

  • In line 6, we initialize the base, exponent, counter variables and result = 1.

  • In line 7, we take the input as base and exponent.

  • In lines 9 and 10, we run a loop and then multiply the base with itself exponent times.

  • In line 12, we print the result.

In this way, we can calculate the power of a number in C++ with loops.

RELATED TAGS

c++
power
communitycreator
RELATED COURSES

View all Courses

Keep Exploring