← Back

Home › Python programs (Hindi)

1 से N तक Natural Numbers का Sum — code और dry run

Read this in English

Problem statement

1 से N तक के numbers का जोड़ निकालना। N = 5 के लिए जवाब 15 है (1+2+3+4+5)। N = 0 पर भी program सही चलना चाहिए — खाली sum 0 होती है।

Approach 1: simple loop

Loop from 1 to N and keep adding into an accumulator. The pattern is the same one behind every running total in every program you will write.

n = 5
total = 0

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

print(total)
# Output: 15

Remember that range(1, n + 1) is needed because the stop value is exclusive — range(1, n) would stop one number early.

Approach 2: reusable function

Gauss's formula does it in one step: n × (n + 1) / 2. Wrap it in a function and use integer division // so the answer stays an integer.

def sum_to(n):
    return n * (n + 1) // 2

print(sum_to(5))       # 15
print(sum_to(100))     # 5050
print(sum_to(0))       # 0

The formula is O(1) — one multiplication whether N is 5 or 5 billion. The loop is O(N). Same answer, wildly different cost.

Approach 3: Pythonic alternative

Python's built-in sum() adds anything iterable, and range is iterable — so the loop collapses into one clear line.

n = 5
print(sum(range(1, n + 1)))   # 15

This is the idiomatic middle ground: no manual accumulator to get wrong, and the intent — "sum of the numbers 1..n" — reads off the page.

Dry run

n = 5 के लिए loop trace करें। शुरुआत: total = 0। i=1 के बाद: 1। i=2: 3। i=3: 6। i=4: 10। i=5: 15। अब formula से cross-check: 5 × 6 // 2 = 15। दो तरीकों का मिलना ही सबसे मज़बूत verification है — और यही जोड़ी off-by-one bug को तुरंत पकड़ती है: अगर गलती से range(1, n) लिखा होता तो जवाब 10 आता, और 10 ≠ 15 बग दे देता।

Common errors

Practice on PyDebug

Concept समझने के बाद इन free problems को browser में solve करें: