#include <stdio.h>
int main() {
int n, sum = 0;
// Input a positive integer from the user
printf("Enter a positive integer: ");
scanf("%d", &n);
// Check if the number is positive
if (n < 1) {
printf("Please enter a positive integer greater than 0.\n");
return 1; // Exit the program if the input is not valid
}
// Calculate the sum of natural numbers
for (int i = 1; i <= n; i++) {
sum += i; // Add the current number to the sum
}
// Output the result
printf("The sum of the first %d natural numbers is: %d\n", n, sum);
return 0; // Indicate that the program ended successfully
}
Explanation:
User Input: The program asks the user to enter a positive integer (n).
Validation: If the entered number is less than 1 (invalid), the program asks for a valid positive number.
Sum Calculation: The program uses a loop to add all numbers from 1 to n. For example, if n = 5, it adds 1 + 2 + 3 + 4 + 5.
Output: It prints the total sum of the first n natural numbers.
Output.
Enter a positive integer: 5
The sum of the first 5 natural numbers is: 15