Write a program to find the sum of N natural numbers using for loop and while loop, respectively
时间: 2024-02-04 11:04:25 浏览: 69
Sure, here's the solution in Python:
Using for loop:
```
# Taking input from user
n = int(input("Enter a positive integer: "))
# Initializing the sum variable
sum = 0
# Using for loop to calculate sum of first n natural numbers
for i in range(1, n+1):
sum += i
# Displaying the sum
print("Sum of first", n, "natural numbers is:", sum)
```
Using while loop:
```
# Taking input from user
n = int(input("Enter a positive integer: "))
# Initializing the sum variable
sum = 0
# Using while loop to calculate sum of first n natural numbers
i = 1
while i <= n:
sum += i
i += 1
# Displaying the sum
print("Sum of first", n, "natural numbers is:", sum)
```
Both programs achieve the same result, i.e., finding the sum of first N natural numbers.
阅读全文