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)
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 % 4equals0, so the condition is true.sum = sum + i→sumis updated tosum + 0, which is0 + 0 = 0.i = i + 2→iis updated to0 + 2 = 2.Second iteration (i = 2):
if i % 4 == 0:→2 % 4equals2, so the condition is false.The value of
sumremains unchanged.i = i + 2→iis updated to2 + 2 = 4.Third iteration (i = 4):
if i % 4 == 0:→4 % 4equals0, so the condition is true.sum = sum + i→sumis updated tosum + 4, which is0 + 4 = 4.i = i + 2→iis updated to4 + 2 = 6.Fourth iteration (i = 6):
if i % 4 == 0:→6 % 4equals2, so the condition is false.The value of
sumremains unchanged.i = i + 2→iis updated to6 + 2 = 8.Fifth iteration (i = 8):
if i % 4 == 0:→8 % 4equals0, so the condition is true.sum = sum + i→sumis updated tosum + 8, which is4 + 8 = 12.i = i + 2→iis updated to8 + 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
Related Questions
Find the output of the following program segment:
for i in range(20, 30, 2): print(i)Find the output of the following program segment:
country = 'INDIA' for i in country: print (i)Write the output of the following:
for i in '123' : print ("Message",i,)Write the output of the following:
for i in [100,200,300] : print (i)