Can you explain how this while loop works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can you explain how this while loop works?

print("enter the value of n") n=int(input()) sum=0 avg=0.0 i=1 while i<10: sum=sum+i i=i+1 print("sum is:",sum) avg=sum/n print("Average is:",avg) NOTE: It's a python code for those who don't have an idea.

13th Oct 2023, 12:19 AM
Bhagya Buch
Bhagya Buch - avatar
3 Answers
+ 1
From line 5 we know 1 is assigned to variable "i", and from line 3, 0 is assigned to variable "sum". The while loop says: When i is less than 10, new sum is equal to old sum + i. In order words, sum is equal to current value of sum plus i. To visualize, it is "sum = 0 + 1", thus sum become 1. After the calculation the program execute "i = i + 1". It works in the same way as explained above. After that it will jump back to while i < 10, and check if i < 10 is true or not. If it is true, the while loop will run again. It will keep repeating until i = 9 + 1, and jump back to while i < 10. In the next while loop, i < 10 become 10 < 10. Since 10 < 10 is not true, the while loop will not be executed and jump to the line "print("sum is:", sum)" and continue.
13th Oct 2023, 2:20 AM
Wong Hei Ming
Wong Hei Ming - avatar
0
The while loop in this code accumulates the sum of the first 9 natural numbers. It begins by initializing 'i' to 1 and runs while 'i' is less than 10. In each iteration, 'i' is added to 'sum,' incrementing 'i' by 1 to avoid an infinite loop. Once 'i' reaches 10, the loop ends. This loop ensures the sum of the first 9 natural numbers is calculated and stored in 'sum.'
13th Oct 2023, 9:12 AM
Ifthekher
Ifthekher - avatar
0
Bhagya Buch , Why do you ask the user for a number to divide by when you hard code a sum of 9 numbers that requires dividing by 9 to get an average? Just hard code the division by 9 as well. Either that, or use the input to determine how many numbers are summed as well as the divisor.
14th Oct 2023, 7:16 AM
Rain
Rain - avatar