Sum of First N Fibonacci Terms

Calculate sum of first n Fibonacci terms.

Logic BuildingIntermediate
Logic Building
# Take n
n = int(input("Enter n: "))

# Calculate sum
if n <= 0:
    sum_fib = 0
elif n == 1:
    sum_fib = 0
elif n == 2:
    sum_fib = 1
else:
    a, b = 0, 1
    sum_fib = 1  # 0 + 1
    for i in range(2, n):
        c = a + b
        sum_fib += c
        a, b = b, c

print(f"Sum of first {n} Fibonacci terms: {sum_fib}")

Output

Enter n: 5
Sum of first 5 Fibonacci terms: 7

Generate Fibonacci terms and accumulate sum.

Key Concepts:

  • Generate Fibonacci sequence
  • Add each term to sum
  • Handle edge cases (n <= 2)