Detailed Print – CSKC
Sign In

Search

siteicon
Solved Problem#CPP#2053 Back

Problem Statement - Powering a number using a loop

Write a c++ program to power a base number with the given exponent by using a for loop.

Solution

		 

Click to open popup

Run Output

6^5 = 7776

Solved Problem Understanding

int base=6,expo=5;
The base and exponent values have been initialised here. These value can also be collected from the user using cin.

int power=1;
This variable has been declared as the place where the output or powered number will be stored. This number can be very large so it may also be declared as long or long long.

for(int i=1;i<=expo;i++)
This loop shall begin with 1 and go till the exponent or value in the power. powering basically means successive power(exponent) times multiplication of same number.

power=power*base;
The successive multiplication step is done inside the loop . This can also be written as power*=base.

cout<<base<<“^”<<expo<<” = “<<power;
This is printing of the final output.

Notes

  • This loop may result in very large numbers in the variable power. The limit checking on input base and exponent number may be desired, otherwise incorrect outputs may result due to shortage of storage space for the resultant number.