Write a Python program to find the sum of the first n natural numbers, where n is provided by the user. Natural numbers are positive integers starting from 1.
Input-Output Examples
plaintext
Example 1:
Input: Enter a number: 10
Output: The sum of the first 10 natural numbers is: 55
Example 2:
Input: Enter a number: 5
Output: The sum of the first 5 natural numbers is: 15
Algorithm to calculate the sum of first N natural numbers
- Start
- Take input: Prompt the user to enter a number
n. - Initialize a variable to store the sum: Set the sum to 0.
- Use a loop to add numbers from 1 to
**n**:- Iterate through the numbers from 1 to
n. - Add each number to the sum.
- Iterate through the numbers from 1 to
- Display the result: Print the sum of the natural numbers.
- End
Python Program to calculate the sum of first N natural numbers
python
# Python program to find the sum of natural numbers
# Take input from the user
n = int(input("Enter a number: "))
# Initialize sum variable to 0
sum_of_numbers = 0
# Calculate the sum of natural numbers from 1 to n
for i in range(1, n + 1):
sum_of_numbers += i # Add each number to the sum
# Display the result
print(f"The sum of the first {n} natural numbers is: {sum_of_numbers}")
Code Explanation
- Taking input from the user:
The program uses theinput()function to take a numbernfrom the user. The input is converted to an integer usingint(). - Initializing the sum variable:
The program initializes a variablesum_of_numbersto 0, which will store the sum of the natural numbers. - Using a loop to calculate the sum:
Aforloop is used to iterate through the numbers from 1 ton. During each iteration, the current number is added tosum_of_numbers. For example, ifn = 5, the loop computes1 + 2 + 3 + 4 + 5 = 15. - Displaying the output:
Theprint()function is used to display the sum of the natural numbers using an f-string to format the output neatly.