Example HTML page

# A Python program to add first n natural numbers

In this post i am writing a python program that prints the sum of first n natural numbers. We know that 1,2,3 … n are the natural numbers. With the following program the sum of first n natural numbers are calculated as:

Let a natural number be 5. The first n natural numbers of 5 are 1,2,3,4 and 5. Then their sum is 1+2+3+4+5=15.

The following is the formula to evaluate the sum of first n natural numbers.

 1+ 2+ … + n = n(n+1) / 2

Program

```num=int(input("Enter a number "))
sum = 0
i = 1
while i <= num:
sum = sum + i
i = i+1
print( "The sum of first",num,"natural number is  ",sum)

```

Output

 Enter a number 26 The sum of first 26 natural number is  351

Explanation

A natural number is given as input and is stored in a ‘num’ variable. The sum is initialized to 0 and counter(i) is set to 1(since 0+1=1). By using while loop we can check the condition whether the counter(i) is less than or equal to the input number(num). If the condition is true then the sum is added with the counter value i and the counter value of i increments by 1.This iteration continues till the condition becomes false and finally prints the sum.

By using for loops also we can print the sum of first n natural numbers. Here we go.

```n = int(input("Enter a number = "))
average = 0
sum = 0
for num in range(0,n+1):
sum = sum+num
print("Sum of first ", n, "natural numbers is: ", sum )

```

Output

 Enter a number = 6 Sum of first  6 natural numbers is:  21

Example HTML page