Write a python program to perform Addition of First 10 Natural numbers by using While Looping Statement
.
Description
This Python code calculates the sum of the first 10 natural numbers using a 'while' loop. It initializes variables 'n' and 'sum,' then uses a 'while' loop to accumulate the sum, and finally displays the result to the user.
Code
program4c.py
n=10
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("the sum of first 10 natural numbers is",sum)
Explanation of above code
- This Python code is a program to calculate the sum of the first 10 natural numbers.
- It initiates by initializing a variable 'n' with the value 10, which represents the number of natural numbers to be summed.
- Additionally, it initializes the variable 'sum' to 0, which will accumulate the sum.
- The code establishes a 'while' loop with the condition
i <= n,
where 'i' starts at 1. This loop continues to execute as long as 'i' is less than or equal to 'n.' - Inside the loop, it updates the 'sum' by adding the current value of 'i' to it using 'sum = sum + i.'
- Simultaneously, it increments 'i' by 1 in each iteration with 'i = i + 1.'
- Following the loop, the code prints a message, 'the sum of the first 10 natural numbers is,' followed by the final value of 'sum.'
- The 'while' loop accumulates the sum of the first 10 natural numbers, and this sum is displayed to the user.
- When executed, the code will print 'the sum of the first 10 natural numbers is 55' because the sum of the numbers from 1 to 10 is indeed 55. This code demonstrates the use of a 'while' loop for cumulative calculations, applicable to similar summation problems.