need some explanation

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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

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;
} 
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).


Let's give an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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 


Hope I could help,
~ Raul ~
Last edited on
thanks all for your help :D
Topic archived. No new replies allowed.