T
T
TheForgetDragon2016-07-20 18:34:15
C++ / C#
TheForgetDragon, 2016-07-20 18:34:15

How to understand the code mechanism?

int e;
int result;
for (int i = 0; i < 10; i++)
{
    result = 1;
    e = i;
    while (e > 0)
    {
        result *= 2;
        e--;
    }
    Console.WriteLine("2 в степени " + i + " равно " + result);
}

Output:
2 to the power of 0 is 1
2 to the power of 1 is 2
2 to the power of 2 is 4
2 to the power of 3 is 8
2 to the power of 4 is 16
2 to the power of 5 is 32
2 to the power of 6 is 64
2 to the power of 7 is 128
2 to the power of 8 is 256
2 to the power of 9 is 512
Problem:
I can't figure out how the code works, namely in the while function.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
Oleg Pogrebnyak, 2016-07-20
@S0HardCore

For each iteration of the outer loop (for), namely, all but the first one (where i = 0) there will be a while loop with the number of iterations equal to i. You can think of it like this:
i = 5
while (5 > 0)
{
...
i--;
}
while (4 > 0) { ... i--; }
...
while (1 > 0) { ... i--; }
End

H
heartdevil, 2016-07-20
@heartdevil

i=0
e=0
while(0>0)
i=1
e=1
while(1>0)->1 iteration 1
i=2
e=2
while(2>0)->2 iterations 2,1
i= 3
e=3
while(3>0)->3 iterations 3,2,1
...
i=9
e=9
while(9>0)->9 iterations 9,8,7,6,5,4, 3,2,1

A
Alexander Volkov, 2016-07-21
@a_volkov1987

Seriously? You have an IDE with step-by-step program execution and the ability to monitor the contents of variables. Feel free to look at what and when changes during execution.

D
Dmitry Nesterov, 2016-07-22
@Guo

while - the same loop with a precondition as for

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question