Cycle 01
Lab Cycle 1 — Control Flow, Loops & Functions
Summation of Alternating Series (1 - 2 + 3 - 4 + ... +/- n)
Problem Statement
Write a Python program to print the summation of the following alternating series up to n terms: 1 - 2 + 3 - 4 + 5 - 6 + 7 - ... +/- n.
def calculate_series_sum(n):
total_sum = 0
terms = []
for i in range(1, n + 1):
if i % 2 != 0: # Odd term (positive)
total_sum += i
terms.append(f"+{i}" if i > 1 else f"{i}")
else: # Even term (negative)
total_sum -= i
terms.append(f"-{i}")
return total_sum, " ".join(terms)
def main():
try:
n = int(input("Enter number of terms (n >= 1): "))
if n < 1:
print("Please enter a positive integer greater than or equal to 1.")
return
total, series_str = calculate_series_sum(n)
print(f"\nSeries: {series_str}")
print(f"Summation up to {n} terms = {total}")
except ValueError:
print("Invalid input! Please enter a valid integer.")
if __name__ == "__main__":
main()
Question 4 of 4