Introduction:
This Python program calculates and displays the sum of the first n natural numbers. The value of n is passed as an argument to the program. The program uses a for loop to iterate from 1 to n and adds each number to the sum. Finally, it prints the sum of the first n natural numbers.
Code:
#Program to find the sum of first n natural numbers
#The requirements are:
#1. n be passed as an argument
#2. Calculate sum of first n natural numbers
#3. Display the sum
#function header
def sumSquares(n): #n is the parameter
sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum of first",n,"natural numbers is: ",sum)
num = int(input("Enter the value for n: "))
#num is an argument referring to the value input by the user
sumSquares(num) #function call
Logic:
- The program defines a function sumSquares that takes n as a parameter.
- It initializes a variable sum to 0.
- Then, it uses a for loop to iterate from 1 to n and adds each number to the sum.
- After the loop, it displays the sum of the first n natural numbers.
- The main part of the program prompts the user to enter the value for n, reads it using the input function, and calls the sumSquares function with the provided value of n.
Output:
Enter the value for n: 12
>> The sum of first 12 natural numbers is: 78