Logic Building
# Take n as input
n = int(input("Enter n: "))
# Calculate sum
sum = 0
for i in range(1, n + 1):
sum += i
print(f"Sum of first {n} natural numbers: {sum}")Output
Enter n: 5 Sum of first 5 natural numbers: 15
Accumulate sum by adding each number.
Key Concepts:
- Initialize sum to 0
- Loop from 1 to n
- Add each number to sum
- Formula: n * (n + 1) / 2 (but we use loop)