Monday, March 11, 2024

BCA PART A 3. Find the sum of n natural numbers

 def sum_of_natural_numbers(n):

# Ensure that n is a positive integer
if n <= 0 or not isinstance(n, int):
print("Please enter a positive integer.")
return
# Calculate the sum using the formula: sum = n * (n + 1) / 2
sum_natural_numbers = n * (n + 1) // 2
print(f"The sum of the first {n} natural numbers is: {sum_natural_numbers}")

# Get input from the user
n = int(input("Enter a positive integer (n): "))

# Call the function to find the sum of n natural numbers
sum_of_natural_numbers(n)

Function Definition:

This line defines a function named sum_of_natural_numbers that takes a parameter n. This function will calculate the sum of the first n natural numbers.

Input Validation:

This block of code checks if the input n is a positive integer. If n is not a positive integer or not an integer at all, it prints an error message and exits the function using return.

Sum Calculation:

This line calculates the sum of the first n natural numbers using the formula sum = n * (n + 1) / 2. The // operator is used for integer division to ensure that the result is an integer.

Output:

This line prints the result, indicating the sum of the first n natural numbers.

User Input:

This line prompts the user to enter a positive integer value for n using the input function. The input is then converted to an integer using int().

Function Call:

This line calls the sum_of_natural_numbers function with the user-provided value of n. The function performs the necessary calculations and prints the result.

No comments:

Post a Comment