HomePythonPython Program to Find Sum of First N Natural Numbers

Python Program to Find Sum of First N Natural Numbers

This Python program calculates the sum of the first N natural numbers. It defines a function called calculat_sum that takes an integer n as input and uses a for loop to iterate from 1 to n, adding each number to the sum. The program then prompts the user to enter a positive integer n, calls the calculate_sum function, and prints the result. It’s important to note that the program assumes the user will provide a positive integer as input.

Problem Statement

Write a Python program that calculates the sum of the first N natural numbers.

Inputs:

  • An integer N representing the count of natural numbers to be considered.

Output:

  • The sum of the first N natural numbers.

Python Program to Find Sum of First N Natural Numbers

def calculate_sum(n):
    sum = 0
    for i in range(1, n + 1):
        sum += i
    return sum

# Example usage
n = int(input("Enter a positive integer: "))
result = calculate_sum(n)
print(f"The sum of the first {n} natural numbers is {result}.")

How it Works

The Python program to calculate the sum of the first N natural numbers works as follows:

  1. It defines a function called calculate_sum that takes an integer n as input.
  2. Inside the calculate_sum function, it initializes a variable sum to 0. This variable will store the sum of the natural numbers.
  3. It uses a for loop with the range() function to iterate from 1 to n+1. The loop variable i represents each natural number.
  4. Within each iteration of the loop, it adds the current value of i to the sum variable.
  5. After the loop completes, it returns the final value of sum.
  6. The program prompts the user to enter a positive integer N using the input() function.
  7. It converts the user input to an integer using the int() function and assigns it to the variable n.
  8. It calls the calculate_sum function with the value of n as an argument and assigns the result to the variable result.
  9. Finally, it prints the sum of the first N natural numbers using a formatted string, combining the value of n and result.

Input/ Output

Python Program to Find Sum of First N Natural Numbers

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...