In the code given below to calculate the sum of squares of first 10 natural numbers, find the output. Why the output is so? If the output is not correct then mark the error and write correct code.

n=10

answer=0

while(n>0)

answer=answer+n**2

n=n+1

print(answer)

 

Answer:

The while loop given in the code is an infinite loop ie., the loop will not terminate.

The error is in the update expression ie., n=n+1 or in the test expression ie., while(n>0).

Corrected code:

n=10

answer= 0  

while(n> 0 ): 

    answer=answer+n** 2  

    n=n -1  

print(answer)

OR

n= 1  

answer= 0  

while(n<= 10 ): 

    answer=answer+n** 2  

    n=n+ 1  

print(answer)

 

Ask a doubt
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.