Powering a number using a loop – CSKC
Sign In

Search

Solved Problem #CPP#2053    siteicon   siteicon  

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

TC++ #2053

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

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.


Share

Created: 31-Dec-2017 02:15 | Updated: 14-Dec-2018 00:03|