How to calculate the number of operations that occur during the execution of the for loop?

I had an exam a couple of days ago, and today the instructor gave us a key answer for the exam.

One of the questions:

for ( j = 9; j >= 1; j-- )

Count the number of operations

The result is 20.

Can someone explain how he gets 20 operations from this?

+5
source share
4 answers

20 operations:

set j = 9
check if j(9) >= 1
set j to 8
check if j(8) >= 1
set j to 7
check if j(7) >= 1
set j to 6
check if j(6) >= 1
set j to 5
check if j(5) >= 1
set j to 4
check if j(4) >= 1
set j to 3
check if j(3) >= 1
set j to 2
check if j(2) >= 1
set j to 1
check if j(1)>=1
set j to 0
check if j(0)>=1

for (j = n; j> = 0; j--)

Ok, you start with two operations:

  • (J = n)
  • check (j> = 0).

For all n <0, it stops there.

If n = 0, you get the following:

  • J -
  • check (j> = 0).

If n = 1, you will get another set of them.

So, the number of operations is 2 for n <0 and 2n + 4 for n> = 0.

. , , ( ).

+14

, j 9. :

  • , j >= 1
  • second, j (j--).

( 9 0 ). , j >= 1, , . 1 + 9 * 2 + 1 = 20 .

+3

? .

, :

for (j = 9; j >= 1; j--)

9 j = 1; j 1 = 10; j , = 9;

1 + 10 + 9 = 20 .

0

1 (j = 9). "j--" 9 ; "j >= 1" 10 ( "j >= 1" ), . , 1 + 9 + 10 = 20.

, , , . , , . .:)

0

All Articles