Python program to find sum of first n natural numbers. Give me 2-3 approach. Plz.
Please help me and I need friends.
Answers
Answered by
25
Required Answer:-
Question:
- Write a Python program to find sum of first n natural numbers.
Solution:
This is an easy question. You can try all these approaches.
1. Approach 1. (Using for loop)
n=int(input("Enter n - "))
s=0
for i in range(1,n+1):
s+=i
print("Sum of first ",n," terms is: ",s)
2. Approach 2 (Using while loop)
n=int(input("Enter n - "))
s,i=0,1
while i<=n:
s+=i
i+=1
print("Sum of first ",n," terms is: ",s)
3. Approach 3 (In one line)
print("Sum is: ",sum(i for i in range(0,int(input("Enter n: "))+1)))
Logic:
We will take n as input. n means the number of terms for the sum. For example, n=10,11..
Now, we will create a loop that runs n times. After each iteration, the value of the loop variable is added to the sum variable. Time to print.
Output is attached.
Attachments:
Similar questions