hello ..
can you explain what would happen here in this program please ?
.......
using namespace std;
int main()
{
int x, y, i, power;
i = 1;
power = 1;
cout << "Enter base as an integer: ";
cin >> x;
cout << "Enter exponent as an integer: ";
cin >> y;
while ( i <= y ) {
power *= x;
++i;
}
cout << power << endl;
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int x, y, i, power;
i = 1;
power = 1;
cout << "Enter base as an integer: ";
cin >> x;
cout << "Enter exponent as an integer: ";
cin >> y;
while ( i <= y ) {
power *= x;
++i;
}
cout << power << endl;
return 0;
}
The explanation is that you will enter a number 'X' and a number 'Y' representing the base and exponent. You are going to calculate xy.
"while ( i <= y )" means that the loop will run for 'y' times.
So "power *= x" is the same as "power = power * x", which means that at each step, your power will be equal to the last result times 'x'.
"++i" means incrementing the variable 'i' which will make the program work (if you don't use that, it will be an infinite loop).
// This is not a C++ code, just example / explanation
Let x = 2, y = 3;
i = 1;
power = 1;
Step 1:
while ( 1 <= 3 ){
power = power * 2; // power = 1 * 2 = 2;
++i; // i = i + 1 = 1 + 1 = 2;
}
Step 2:
while ( 2 <= 3 ){
power = power * 2; // power = 2 * 2 = 4;
++i; // i = i + 1 = 2 + 1 = 3;
}
Step 3:
while ( 3 <= 3){
power = power * 2; // power = 4 * 2 = 8;
++i; // i = i + 1 = 3 + 1 = 4;
}
Step 4:
while ( 4 <= 3) // There is no step 4;
The final result is --> power = 8; // xy = 23 = 8