Click here to Skip to main content
15,868,049 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
A code which only and only contains these things:
Contains a variable for the base
Contains a variable for the exponent
Uses a for loop to perform the power function(we can use a variable here for iteration)
Outputs the result to the console window

What I have tried:

I have tried it many times but failed to do this by using only two variables.
An example of what i tried:
int base;
int exponent;
int c;
c=exponent;
exponent=base;	
for (int i = 1; i < c; i++) {

exponent*= base;
}
std::cout << exponent;
Posted
Updated 28-Jul-18 8:55am

Let the loop run downwards. Then the exponent value can be assigned to the loop variable initially. Because you have to initialise the result too and will use exponent, this must be done after initialising the loop variable. Fortunately, C/C++ for loops allow multiple statements in the init expression.

Putting it all together and initialising the result with one to get the correct result when exponent is zero (requires one more iteration than in your code):
C++
for (int i = exponent - 1, exponent = 1; i >= 0; i--)
{
    exponent *= base;
}
 
Share this answer
 
Comments
CPallini 27-Jul-18 4:18am    
Nice. 5.
Member NFOC 27-Jul-18 9:32am    
Thanks it helped. Also i found a another similar code as yours by doing some adjustments like this:
int a;
int b;
std::cout << "Let's find the b power of a: " << std::endl;
std::cout << "Enter b: ";
std::cin >> b;
std::cout << "Enter a: ";
std::cin >> a;

for (int i = b-1 , b = 1; i >= 0; i--) {

//std::cout << "b: " << b << std::endl;
b *= a;
//std::cout << "i: " << i << std::endl;
if (i == 0) {
std::cout << "b: " << b << std::endl;
}

}
Jochen Arndt 27-Jul-18 9:48am    
That is identical besides using different variable names and printing the result inside the loop. The latter is even wrong because nothing would be printed when the exponent is zero (then the body of the loop is never entered).
Member NFOC 28-Jul-18 15:22pm    
Sir I'm thinking your code is also not under the conditions predefined. As your code is taking more than three variables(three variables should be like this two for exponents and base and one in for loop), by taking b inside the loop you are making a code similar to this:
for (int i = 0, result = 1; i < expo; i++ ) {
result *= base;
}
Nelek 28-Jul-18 16:09pm    
elegant, nice :)
Quote:
I have tried it many times but failed to do this by using only two variables.

What prevent you from using c or exponent as the loop variable ?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900