Computer Science, asked by ahmedpumpwala4311, 11 months ago

How many times will the following for loop be executed? for (a = 0; a <= 10; a = a + 2) { ... statements ... }

Answers

Answered by shilpa85475
0

Let's run the application dry-run. The loop begins with 0. So it's valid to 0<10.

Explanation:  

  • The loop begins with 0. So it's valid to 0<10. The sentence in the block is then executed.
  • As long as there is no statement of loop endings, the value of I is decreased to-1, which is lower than 10.
  • This process continues until I hit the int boundary. The variable int now can store 2 bytes or 4 bytes of data, depending on the compiler.

Let's take the two scenarios into account:

1. In this case, int will store a value of-2 ^ 15=-32768 in minus 2 Bytes(= 8x2 bits=16 bits). Thus, when the I value reaches this value, the value will decrease further, making the i=32767 value. The loop is now done 32767 > 10. This is why the number of iterations is 32769.

2. If int saves 4 bytes (= 32 bits): this is the same logic. The only difference is that the value of -2147483648 is dragged down. This time, there are 2147483649 iterations.

Similar questions