Python Practice › Loop Programs › Program 18

Sum of odd numbers 1 to n

EasyLoop Programs · 18 of 90

Write a Python program to find the sum of all odd numbers from 1 to n.

Advertisement
Input
n = 20
Output
Sum of odd numbers: 100

Approach

  1. Loop from 1 with a step of 2.

Solution

Python
n = 20total = 0for i in range(1, n + 1, 2):    total += iprint("Sum of odd numbers:", total)
Output
Sum of odd numbers: 100
Note

The sum of the first k odd numbers is k², so for n = 20 (ten odd numbers) the answer is 100.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs