Here is how to do exponentiation asking the user for two numbers:
The program should ask the user for two numbers “a” and “b”, and then, raise “a” to the power of “b”. In order to do this, we will be using 4 variables:
- long a;
- long b;
- long power=1;
- long counter=0;
We will be using a “do, while” loop, therefore, we need a variable to use as a counter and asign to it the value of 0.
After asking the user for both numbers a and b, you will create a “do while” loop that works (while counter < b), because we will need the loop to work until we get to the value of b.
Lets remember the formula for exponentiation: photo by: http:/
Our do while loop, will multiply “a”, “b” times, which means that the loop should multiply “a x a” as many times as the variable “b” states.
Here is how it should look:
do{
power=power*a;
counter=counter+1;
}while(counter < b);
After that you can print out the new value of your variable “power” in order to show your result.
Here is a picture of the code and how it should run:
solution for q2.cpp by carlos green is licensed under a Creative Commons Attribution 4.0 International License.