We can calculate the sum of numbers from 1 to N by using for loop or by using mathematical formula.
sum of natural numbers = n(n+1)/2
Method 1 (by using for loop) :
Code :
num = int(input("Input Any Number : "))
sum = 0
for i in range(1,num+1):
sum += i
print("Sum of",num,"terms is :",sum)
Output :
Input Any Number : 100
Sum of 100 terms is : 5050
Method 2 (by using formula) :
Code :
num = int(input("Input Any Number : "))sum = int(num*(num+1)/2)print("Sum of",num,"terms is :",sum)Output :
Input Any Number : 100Sum of 100 terms is : 5050
In this method you have to type cast sum variable to integer otherwise the final output will be of the float type i.e. 5050.0
num = int(input("Input Any Number : "))
sum = int(num*(num+1)/2)
print("Sum of",num,"terms is :",sum)
Output :
Input Any Number : 100
Sum of 100 terms is : 5050
In this method you have to type cast sum variable to integer otherwise the final output will be of the float type i.e. 5050.0
0 Comments
Ask Your Queries in the comments