Select Page

# C++ Program to Calculate Power of a Number

by | Jan 31, 2023 | C++, C++ Programs

Home » C++ » C++ Programs » C++ Program to Calculate Power of a Number

## Introduction

In this program, you will learn to calculate the power of a number.

The user will be asked to enter an integer as the base value and the power value, which will be the exponent of the base number.

For example, 9 raised to power 3 means 93= 9*9*9=721, where 9 is the base value and 3 is the exponent.

To understand the program, you should know about

1. Operators

2. while and do-while loop

## Program

```#include<iostream>
using namespace std;
int main()
{
float b; // b is base number
cout<<"Enter the base value: ";
cin>>b;

int p; // p is the power or exponent
cout<<"Enter the value of exponent: ";
cin>>p;

float result=1;
while(p!=0) //condition
{
result=result*b;
p--;
}
cout<<"Result: "<<result;
return 0;
}```

## Explanation

‘b’ is the variable for the base number, and ‘p’ is the power of the base number.

float result=1;

To store the final result variable, ‘result’ is initialized with 1.

while(p!=0)

If the above condition gives a true result, then the body of the while loop is executed.

Since ‘p’ is 3 thus, the condition becomes true, and the value of the base entered by the user is 8 therefore,

result=result*b; it will assign 1*8 i.e., result=8

p–; ‘p’ gets decremented to 2

the condition becomes true for p=2 thus,

result=result*b; it will assign 8*8 i.e., result=64

p–; ‘p’ gets decremented to 1

the condition becomes true for p=1 thus,

result=result*b; it will assign 64*8 i.e., result=512

p–; ‘p’ gets decremented to 0

the condition becomes false for p=0 thus,

the final result is 512