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)
Input:
Enter a number: 5
Sample Output:
Sum = 15
Top comments (0)