Write a program to compute the sum 1 − 2 + 3 − 4 + ··· + 1999 − 2000 .
# initialize the sum to 0
sum = 0
# loop through the numbers from 1 to 2000
for i in range(1, 2001):
# add or subtract the current number from the sum
# depending on whether it is odd or even
if i % 2 == 0:
sum -= i
else:
sum += i
# print the sum
print(sum)
This program first initializes a sum variable to 0. It then loops through the numbers from 1 to 2000 and adds or subtracts the current number from the sum depending on whether it is odd or even. Finally, it prints the sum.
If you run the program, it will compute and print the sum of 1 − 2 + 3 − 4 + ··· + 1999 − 2000. For example, you might see something like:
0
This is the result of the computation.
0 Comments