Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

How to compute the sum of even numbers

Pranavi Anoushka Tirumalasetty

Sum of even numbers

We can run this program using for loop, while loop, or do while to find the sum of even numbers within a given range of numbers.

In general, even numbers are those numbers that are divisible by 2.

The following can be used to write the logic, as shown as below:

# computing the sum of even numbers
sum = 0
for i in range(10):
 if i % 2 == 0:
   sum = sum + i

For a given even number, we can get its subsequent even number by adding 2 in it.

The following can be used to write the logic in the while loop, as shown below:

# computing the sum of even numbers
sum = 0
i = 0
while(i < 11):
   sum = sum + i
   i = i + 2
svg viewer
Iteration of the loop

The two ways of writing the code to determine the sum of integers in Python language are given below:

sum=0
for i in range(15):
  if i%2==0:
    sum=sum+i
print("sum =",sum)

RELATED TAGS

python
community creator

CONTRIBUTOR

Pranavi Anoushka Tirumalasetty
RELATED COURSES

View all Courses

Keep Exploring