Computing the summation of all the numbers from 1 to n
is a common task in programming, and there are multiple ways to do it in Python. In this article, we will explore two approaches: using a loop and using a mathematical formula.
sum of n numbers in python using for loop
One way to compute the summation is to use a loop. This approach involves iterating over the numbers from 1 to n
and adding each number to a result variable. Here’s an example of how to do this:
def sum_from_1_to_n(n):
result = 0
for i in range(1, n + 1):
result += i
return result
print(sum_from_1_to_n(5)) # Output: 15 (1 + 2 + 3 + 4 + 5)
print(sum_from_1_to_n(10)) # Output: 55 (1 + 2 + 3 + ... + 10)
In the above example, we define the sum_from_1_to_n()
function that takes an integer n
as an argument and returns the summation of all the numbers from 1 to n
. The function initializes a variable result
to 0 and uses a for
loop to iterate over the numbers from 1 to n
, adding each number to result
. After the loop, the function returns the result
sum of n numbers in python using mathematical formula
Another way to compute the summation is to use a mathematical formula. This approach involves using a formula that takes n
as an input and returns the summation of all the numbers from 1 to n
. Here’s an example of how to do this:
def sum_from_1_to_n(n):
return (n * (n + 1)) // 2
print(sum_from_1_to_n(5)) # Output: 15 (1 + 2 + 3 + 4 + 5)
print(sum_from_1_to_n(10)) # Output: 55 (1 + 2 + 3 + ... + 10)
In the above example, we define the sum_from_1_to_n()
function that takes an integer n
as an argument and returns the summation of all the numbers from 1 to n
using the mathematical formula. Then, we call the function with different inputs and print the expected output for each test case.
sum of n numbers using while loop in python
To compute the summation of all the numbers from 1 to n
in Python using a while
loop, you can iterate over the numbers and add them to a result variable. Here’s an example of how to do this:
def sum_from_1_to_n(n):
result = 0
i = 1
while i <= n:
result += i
i += 1
return result
print(sum_from_1_to_n(5)) # Output: 15 (1 + 2 + 3 + 4 + 5)
print(sum_from_1_to_n(10)) # Output: 55 (1 + 2 + 3 + ... + 10)