Write a Python algorithm that asks the user to enter an integer n and display the value of the sum = 1 + 2 + … + n
# ask user to enter n = int(input("Enter a positive integer: ")) # initializing the sum sum = 0 # browsing through all integers from 1 to n for i in range(1, n+1): sum += i print("The sum of the first", n, "positive integers is: ", sum)
In this program:
- we first ask the user: to enter a positive integer n using the input() function and convert it to an integer using the int() function.
- We then initialize a variable sum to 0: which will be used to keep track of the sum of the integers.
- We use a for loop: to iterate over the integers from 1 to n using the range() function.
- For each integer i: we add it to the current value of sum.
- Finally, we use the print() function: to display the result of the sum.
One thought on “Solution Exercise 8: algorithm python to compute the sum of first n integers”
[…] Exercise 8 || Solution […]