Reputation: 3
I understand every cog in this code with the exception of one part: the "e--;" within the While loop. Can anybody explain its importance to me?
public class Power
{
public static void Main()
{
int e;
int result;
for(int i=0; i < 10; i++)
{
result = 1;
e = i;
while(e > 0)
{
result *= 2;
e--;
}
Console.WriteLine(string.Format("2 to the {0} power is {1}", i, result));
}
}
}
Upvotes: 0
Views: 112
Reputation: 927
e
is your counter variable. It will repeat the while
loop until the result has been multiplied the specified number of times (which is whatever i
is when the loop started). As others have stated, e--
just decrements the value of e
by one. You can read more here. This means that, in the code you provided, it will multiply result
by 2 e
times which mathematically will compute 2^i
(i.e. 2^0 = 1
, 2^1 = 2
, 2^2 = 4
, etc.).
Upvotes: 1
Reputation: 6134
The e--
just decrements the value of e
. It is equivalent to e = e - 1;
.
The reason you decrement the value is to eventually exit of the while
loop; once you set e
to the value of i
, the loop will run indefinitely unless the value of e
becomes less or equal to zero, which makes the while
loop condition of e > 0
false.
In the larger picture, you are using e
to stored the current value of i
and then use it to execute i
times the statement result *= 2;
. In other words, you are using e
to count how many times the variable result
needs to be multiplied by 2
during the current iteration of the outer for
loop.
This is similar to doing something like,
for (int i=0; i < 10; i++)
{
result = 1;
e = 0;
for (e = i; e > 0; e--)
{
result *= 2;
}
}
Since the while
loop is really acting as a for
loop.
Upvotes: 1
Reputation: 203802
The idea here is to simply multiply result
by 2 i
times. It does this by setting e
to i
, subtracting one each iteration of the loop, and looping while it's positive. This means that the while
loop will always loop i
times. You could just as easily (and arguably more clearly) write:
for(int e = 0; e < i; e++)
result *= 2;
Upvotes: 1
Reputation: 6103
You're looking at a postfix decrement operator.
It evaluates the value of e
and then subtracts one from the value; since it's a standalone statement, it simply subtracts one from e
's value.
Upvotes: 2
Reputation: 101680
while(e > 0)
This means that your loop will run as long as e
is greater than zero. e--
is decrementing e's value
on each iteration. If you didn't decrement it inside of your loop then you will get an infinite loop because your condition will become always true and your loop won't end.
Upvotes: 1
Reputation: 6720
e-- means it will decrease 1 in each loop, e++ will increase 1
check this article http://msdn.microsoft.com/en-us/library/36x43w8w.aspx
Upvotes: 0