DEV Community

Bala Murugan
Bala Murugan

Posted on

Sum of First n Numbers

Definition:

The sum of first n numbers means adding all numbers from 1 to n.

Example:

If n = 5

Sum = 1 + 2 + 3 + 4 + 5

Sum = 15

Algorithm:

1.Start

2.Read the number n

3.Initialize i = 1 and sum = 0

4.Check whether i <= n

5.Add i to sum

6.Increment i by 1

7.Repeat steps 4 to 6 until i > n

8.Print the sum

9.Stop

Flowchart:

Start
|
Input n
|
i = 1
sum = 0
|
i <= n ?
/ \
Y N
| |
sum=sum+i
|
i=i+1
|
Back to i<=n

N
|
Print Sum
|
Stop

code:

n = int(input("Enter a number: "))

i = 1
sum = 0

while i <= n:
    sum = sum + i
    i += 1

print("Sum =", sum)

Enter fullscreen mode Exit fullscreen mode
Input:

Enter a number: 5

Sample Output:

Sum = 15

Enter fullscreen mode Exit fullscreen mode

Top comments (0)