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
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.
Output
Enter a number = 6
Sum of first 6 natural numbers is: 21 |