Python Program - Find the Sum of Natural Numbers

www.igi‮c.aeditf‬om

here's a Python program that finds the sum of the first n natural numbers:

# Define a function to find the sum of the first n natural numbers
def sum_of_naturals(n):
    sum = 0
    for i in range(1, n+1):
        sum += i
    return sum

# Call the function with n=10
result = sum_of_naturals(10)

# Print the result
print("The sum of the first 10 natural numbers is", result)

In this program, we define a function called sum_of_naturals that takes a single argument n and returns the sum of the first n natural numbers.

To find the sum, we use a for loop that iterates over the range of numbers from 1 to n (inclusive) and adds each number to a running total called sum.

We then return the final value of sum.

In the main program, we call the sum_of_naturals function with n=10 and assign the result to a variable called result.

Finally, we print the result using the print() function and string formatting.

If we run this program, the output will be:

The sum of the first 10 natural numbers is 55

Note that the formula for the sum of the first n natural numbers is n(n+1)/2. This formula can be used to find the sum more efficiently than using a loop. For example, to find the sum of the first 10 natural numbers using the formula, we could write:

n = 10
result = n * (n+1) // 2
print("The sum of the first 10 natural numbers is", result)

This program will produce the same output as the previous program.