78,759 views
29 votes
29 votes
Write a simple nested loop example that sums the even and odd numbers between 5 and 15 and prints out the computation.

User Goddamnyouryan
by
3.1k points

2 Answers

23 votes
23 votes

Final answer:

A simple nested loop can sum even and odd numbers between two values by initializing sum variables, iterating through the range, and conditionally adding to the proper sum based on the number's parity, with final print statements displaying the results.

Step-by-step explanation:

Simple Nested Loop Example for Summing Even and Odd Numbers

When you need to sum even and odd numbers within a range, you can effectively do this using a loop. Here is a straightforward example of using a nested loop to compute and print the sum of even and odd numbers between 5 and 15.

sum_even = 0
sum_odd = 0
for i in range(6, 16):
if i % 2 == 0:
sum_even += i
else:
sum_odd += i

print('Sum of even numbers:', sum_even)
print('Sum of odd numbers:', sum_odd)

This code initializes two variables, sum_even and sum_odd, to store the sums of even and odd numbers, respectively. The loop runs through numbers from 6 to 15 (since 5 is not included in the even or odd sums), and the if-else statement inside the loop checks if a number is even or odd.

User WillMonge
by
2.9k points
27 votes
27 votes

Answer:

for e in range(6, 15, 2):

for o in range(5, 15, 2):

calc = e+o

print(e, "+", o, "=", calc)

Step-by-step explanation:

User Dongx
by
3.0k points