How to Calculate Power of a Number Using C++

The power of a number can be calculated as x^y where x is the number and y is its power. Or simply it can be said that x is the base and y is its exponent. We calculate in math power of a number:

2^3 = 2*2*2 = 8

Calculate Power of a Number Using C++

To get started, create a C++ project using your favorite IDE. In this example, the program will contain the following perceptive section in the code.

/* power of Number */
Preprocessor directive/Header Files:

#include <iostream>
This manual explains to that preprocessor that includes the several materials in iostream header report inside the method just before compilation. This kind of report is essential to get input-output transactions.

This file is known as a header report utilized in older MS-DOS compilers to produce content material end-user lines

This header file declares to the compiler that common mathematical operations will be used in that program.

Using namespace std;
Standard (std) is the standard namespace. Cout, cin and lots of other activities happen to be described in there. That built-in C++ catalog sessions are stored inside the standard namespace.

function main()
When the program run, the compiler execute the code from the main() function. Each program must contain the main() function. If the function does not contain the main function, it causes an error.
int/void is a return value.\


Int/void main()
//body of program

Main Program

#include<iostream>                                 /*Preprocessor directive*/
using namespace std;
 int main()
   int base;                                     /*Values Declaration*/
   int exponent;
   int i;
   int pow=1;                                         
   cout<<"Enter base of the number: ";
   cout<<"Enter exponent of that base : ";                                      /*input values*/
   pow=pow*base;                                        /*power formula*/
   cout<<"power is: "<<pow;
 return 0;


C++ Power of a Number Result


First of all, the compiler goes to header files and understand the basic files and then onward to the main function.

1. Execution starts with the main function.

2. Declare the variables
exponent=> to store exponential value
base=> to store base value
pow => to store final result

3. Take input power and base from user
cin >> base;
cin >> exponent;

4. Now calculate the power of a number
Loop continues till that time when the value of I becomes 1 and the result stores in result=pow

Related Articles


Functional Programming in C++

Calculate Average of Numbers in Arrays using C++

How to reverse an Array in C

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers.

View all posts by Tutorials Panel →

Leave a Reply