In mathematics, the sum of the first n even natural numbers is given by the formula n(n+1).
In this programming task, we will write a program to find the sum of the first n even natural numbers using a while loop.
Simple Code:
n = int(input("Enter a number: "))
sum = 0
i = 1
count = 0
while count < n:
if i % 2 == 0:
sum += i
count += 1
i += 1
print("The sum of first", n, "even natural numbers is:", sum)
Output:
Enter a number: 1874
The sum of first 1874 even natural numbers is: 3513750
Code With Explanation:
# Take input of the number
n = int(input("Enter a number: "))
# Set initial sum to 0, initial number to 1, and count to 0
sum = 0
i = 1
count = 0
# Loop until count is less than n
while count < n:
# Check if the current number is even
if i % 2 == 0:
# Add the current number to the sum
sum += i
# Increment the count by 1
count += 1
# Increment the current number by 1
i += 1
# Print the sum of the first n even natural numbers
print("The sum of first", n, "even natural numbers is:", sum)
Explanation:
The program takes an input of a number and uses a while loop to find the sum of the first n even natural numbers.
The loop continues until count becomes greater than or equal to n.
In each iteration, the current number is checked if it is even using the modulus operator (%).
If it is even, then it is added to the sum, and the count is incremented by 1.
If it is odd, then the loop moves to the next iteration without adding to the sum.
Finally, the program prints the sum of the first n even natural numbers.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.