Slider

Python Program to Calculate Sum of Natural Numbers.

Python Code to Find Sum of Natural Numbers Using for loop. The most efficient way to find the sum of natural numbers is by using a math formula. Formu

Natural numbers are a set of positive integers starting from 1 and continuing indefinitely. They are the numbers you use for counting and ordering. The sum n natural numbers can be calculated using a formula or by using a loop. 


Example:

Input: n = 5
Output: 15

Explanation:
1+2+3+4+5 = 15

The sum of Natural Numbers Using a Loop.

You can easily find the sum of natural numbers using a for or a while loop in Python.

Algorithm:
  • Take the input value n from the user.
  • Initialize a variable S to 0 (to store the sum).
  • Use a for loop to iterate from 1 to n. In each iteration, add the current number to S.
  • Display the sum of n natural numbers as a result.

Python Code to Find Sum of Natural Numbers Using for loop.
# Python code implementation to find sum of natural numbers
def sum_of_natural_numbers_with_loop(n):
    S = 0
    for i in range(1, n + 1):
        S += i
    return S

n = int(input("Enter the value of n: "))

result = sum_of_natural_numbers_with_loop(n)

print(f"Sum of the first {n} natural numbers using a loop is: {result}")
Output:
Enter the value of n: 10
sum of the first 10 natural numbers using a loop is: 55

The Sum of Natural Numbers Using Math.

The most efficient way to find the sum of natural numbers is by using a math formula. Formula: sum = n*(n+1)/2

Example:

Input: n = 10;
Output: 55

Explanation: 
sum = n*(n+1)/2
    = 10*(10+1)/2
    = 10*(11)/2
    = 10*5.5
    = 55

Algorithm:
  • Take the value of n as an input from the user.
  • Initialize a variable sum to 0 to store the sum of natural numbers.
  • Use the mathematical formula to calculate the sum and store the result in the sum variable.
  • Display the value of the sum as a result. 

Python code to find the sum of natural numbers using a formula.
# Python sum of natural numbers
def sum_of_natural_numbers(n):
    S = (n * (n + 1)) // 2
    return S

n = int(input("Enter the value of n: "))

result = sum_of_natural_numbers(n)

print(f"Sum of the first {n} natural numbers is: {result}")
Output:
Enter the value of n: 10
sum of the first 10 natural numbers using a loop is: 55

These are the two Python program that calculates the sum of the first n natural numbers.

0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson
Table of Contents