In mathematics, the sum of the first n odd natural numbers is given by the formula n^2.
In this programming task, we will write a program to find the sum of the first n odd 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, "odd natural numbers is:", sum)
Output:
Enter a number: 4238
The sum of first 4238 odd natural numbers is: 17960644
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 odd
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 odd natural numbers
print("The sum of first", n, "odd 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 odd 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 odd using the modulus operator (%).
If it is odd, then it is added to the sum, and the count is incremented by 1.
If it is even, then the loop moves to the next iteration without adding to the sum.
Finally, the program prints the sum of the first n odd natural numbers.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.