143k views
0 votes
2- (20 points) a) Write a program segment that computes 1 2 3 ... (n - 1) n , where n is a data value that is entered by the user. b) Use an if statement that compares the computed sum above to (n * (n 1))/2 and displays a message that indicates whether the values are the same or different. c) What do you conclude for all values of n

1 Answer

5 votes

Answer:

total = 0

n = int(input("Enter a number: "))

for i in range(1, n+1):

total += i

if (n * (n + 1) / 2) == total:

print("Values are the same")

else:

print("Values are different")

Step-by-step explanation:

I believe the series you wrote should be 1+2+3 ... +(n-1)+n.

The sum of the natural numbers up to n can be calculated as n(n+1)/2.

The code is written in Python.

Initialize a variable total to hold the total

Ask the user for input, n

Create a for loop that iterates from 1 to n

Add all the numbers in the range to the total

When the loop is done, check if the total is equal to given formula. If they are equal, print same.Otherwise, print different

User Biziclop
by
5.0k points