Program to find the sum of all even numbers between two given numbers using a while loop in Python:
# take user input for the two numbers
start_num = int(input("Enter the start number: "))
end_num = int(input("Enter the end number: "))
# initialize sum variable
sum_even = 0
# use while loop to find even numbers and add them to the sum
while start_num <= end_num:
if start_num % 2 == 0:
sum_even += start_num
start_num += 1
# print the sum of even numbers
print("The sum of even numbers between", start_num, "and", end_num, "is", sum_even)
In this program, we take user input for the two numbers between which we need to find the sum of even numbers. We initialize a variable sum_even
to 0, which we will use to accumulate the sum of even numbers.
Next, we use a while loop to iterate over all numbers between the start and end numbers. For each number, we check if it is even by using the modulus operator %
to check if it is divisible by 2. If it is even, we add it to the sum_even
variable. Finally, we increment the value of the start number by 1 and continue the loop until we reach the end number.
After the loop completes, we print the sum of even numbers between the start and end numbers using a formatted string.
Comments
Post a Comment