In this tutorial, we are going to write a program to find the sum of the first n natural numbers using a while loop.
In mathematics, the sum of the first n natural numbers is given by the formula n(n+1)/2.
So, this is a Python program to find the sum of the first n natural numbers using a while loop.
Simple Code:
n = int(input("Enter a number: "))
sum = 0
i = 1
while i <= n:
sum += i
i += 1
print("The sum of first", n, "natural numbers is:", sum)
Output:
Enter a number: 1589
The sum of first 1589 natural numbers is: 1263255
Code With Explanation:
# Take input of the number
n = int(input("Enter a number: "))
# Set initial sum to 0 and initial number to 1
sum = 0
i = 1
# Loop until i is less than or equal to n
while i <= n:
# Add i to the sum
sum += i
# Increment i by 1
i += 1
# Print the sum of the first n natural numbers
print("The sum of first", n, "natural numbers is:", sum)
Explanation:
The program takes an input of a number and uses a while loop to find the sum of the first n natural numbers.
The loop continues until i becomes greater than n.
In each iteration, the current value of i is added to the sum of natural numbers, and then i is incremented by 1.
Finally, the program prints the sum of the first n natural numbers.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.