EX 6.1 How many iterations will the following for loops execute? for (int i = 0; i < 20; i+ +) { } for (int i = 1; i <= 20; i+ +) { }

Question

EX 6.1 How many iterations will the following for loops execute? for (int i = 0; i < 20; i+ +) { } for (int i = 1; i <= 20; i+ +) { } for (int i = 5; i < 20; i+ +) { } for (int i = 20; i > 0; i- -) { } for (int i = 1; i < 20; i = i + 2) { } for (int i = 1; i < 20; i *= 2) { }

in progress 0
Ivy 3 months 2022-02-19T09:42:54+00:00 1 Answer 0 views 0

Answers ( )

    0
    2022-02-19T09:44:20+00:00

    Answer:

    20, 20, 15, 20, 10, and 5 iterations respectively

    Step-by-step explanation:

    The loop “for (int i = 0; i < 20; i+ +)” starts at i=0 and increases the counter i by 1 at the end of each iteration. The counter must be less than 20, so the values of i in the loop are 0,1,2,3,…,19. These are 20 values, and thus the code iterated 20 times.

    The loop “for (int i = 0; i < 20; i+ +)” starts at i=1 and increases the counter i by 1 at the end of each iteration. The counter can’t exceed 20, so the values of i in the loop are 1,2,3,4,…,20. These are 20 values, and thus the code iterated 20 times.

    Similarly, in “for (int i = 5; i < 20; i+ +)” i takes the 15 values are 5,6,7,…,19. Hence, the code iterated 15 times.

    The loop “for (int i = 20; i > 0; i- -)” starts at i=20 and decreases the counter i by 1 at the end of each iteration, so the values of i in the loop are 20,19,18,…,1. These are 20 values, then we have 20 iterations.

    The loop “for (int i = 1; i < 20; i = i + 2)” starts at i=1 and increases the counter i by 2 at the end of each iteration. The values of i in the loop are 1,3,5,7,…,19. These are 10 values, and thus the code iterated 10 times.

    The loop “for (int i = 0; i < 20; i+ +)” starts at i=1 and multiplies the counter i by 2 at the end of each iteration, so the values of i in the loop are 1,2,4,8,16. Then we have 5 iterations.

Leave an answer

45:7+7-4:2-5:5*4+35:2 =? ( )