Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
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
Run Output
6^5 = 7776
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.