Why is the output is 6 in the following code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is the output is 6 in the following code?

i = 0 x = 0 while i < 4: x += i i += 1 print(x)

8th Dec 2022, 1:04 AM
Haru
Haru - avatar
3 Answers
+ 6
in this code the while loop will continue to run as long as the value of the i variable is less than 4. Inside the loop, the value of i is added to the value of the x variable, and then i is incremented by 1. When the loop starts, i is 0 and x is 0. Since 0 is less than 4, the loop body will be executed. Inside the loop, 0 is added to x, and then i is incremented to 1. This means that x is now 1 and i is now 1. The loop will now repeat with the new values of x and i. Since 1 is less than 4, the loop body will be executed again. Inside the loop, 1 is added to x, and then i is incremented to 2. This means that x is now 3 and i is now 2. The loop will repeat with these new values of x and i. Since 2 is less than 4, the loop body will be executed again. Inside the loop, 2 is added to x, and then i is incremented to 3. This means that x is now 5 and i is now 3.
9th Dec 2022, 11:36 AM
Sadaam Linux
Sadaam Linux - avatar
+ 6
The loop will repeat with these new values of x and i. Since 3 is less than 4, the loop body will be executed again. Inside the loop, 3 is added to x, and then i is incremented to 4. This means that x is now 8 and i is now 4. Since 4 is not less than 4, the while loop will terminate. The final value of x is 8, so when the print(x) statement is executed, the value 8 will be printed to the screen. Therefore, the output of this code will be 6.
9th Dec 2022, 11:38 AM
Sadaam Linux
Sadaam Linux - avatar
+ 4
Haru x = 1 + 2 + 3 = 6 Every time i is incrementing so i = 1, 2, 3 and x = 6
8th Dec 2022, 3:03 AM
A͢J
A͢J - avatar