Informatics Practices

Find the output of the following program segment:

i = 0; sum = 0
while i < 9:
      if i % 4 == 0:
         sum = sum + i
      i = i + 2
print (sum)

Python Control Flow

4 Likes

Answer

12

Working

Let's break down the code step-by-step:

1. Initial Assignments:

i = 0
sum = 0

Two variables are initialized: i is set to 0, and sum is set to 0.

2. while i < 9: → This loop continues to execute as long as i is less than 9.

3. Inside the while loop:

  • First iteration (i = 0):

  • if i % 4 == 0:0 % 4 equals 0, so the condition is true.

  • sum = sum + isum is updated to sum + 0, which is 0 + 0 = 0.

  • i = i + 2i is updated to 0 + 2 = 2.

  • Second iteration (i = 2):

  • if i % 4 == 0:2 % 4 equals 2, so the condition is false.

  • The value of sum remains unchanged.

  • i = i + 2i is updated to 2 + 2 = 4.

  • Third iteration (i = 4):

  • if i % 4 == 0:4 % 4 equals 0, so the condition is true.

  • sum = sum + isum is updated to sum + 4, which is 0 + 4 = 4.

  • i = i + 2i is updated to 4 + 2 = 6.

  • Fourth iteration (i = 6):

  • if i % 4 == 0:6 % 4 equals 2, so the condition is false.

  • The value of sum remains unchanged.

  • i = i + 2i is updated to 6 + 2 = 8.

  • Fifth iteration (i = 8):

  • if i % 4 == 0:8 % 4 equals 0, so the condition is true.

  • sum = sum + isum is updated to sum + 8, which is 4 + 8 = 12.

  • i = i + 2i is updated to 8 + 2 = 10.

  • Sixth iteration (i = 10):

  • The loop condition while i < 9: is no longer true (10 is not less than 9), so the loop terminates.

4. print(sum) → After exiting the loop, the value of sum is printed.

Summarizing all updates to sum:

  • After the first iteration, sum = 0.
  • After the third iteration, sum = 4.
  • After the fifth iteration, sum = 12.

Therefore, the output of the code is:

12

Answered By

2 Likes


Related Questions