C Program to Calculate the Sum of Natural Numbers
#include <stdio.h>
int main() {
int n, sum = 0;
// Prompt the user to enter a number
printf("Enter a positive integer: ");
scanf("%d", &n);
// Sum of natural numbers
for (int i = 1; i <= n; ++i) {
sum += i;
}
// Display the result
printf("Sum of natural numbers from 1 to %d is: %d\n", n, sum);
return 0;
}
Explanation of the Program:
Variable Declaration:
int n, sum = 0;
: We declare two integer variables.n
will hold the number input by the user, andsum
will store the cumulative sum of natural numbers.
Input:
- The program prompts the user to enter a positive integer. This input is stored in the variable
n
usingscanf()
.
- The program prompts the user to enter a positive integer. This input is stored in the variable
Logic:
- A
for
loop starts ati = 1
and runs untili
is less than or equal ton
. In each iteration, the loop adds the value ofi
to thesum
variable.
- A
Output:
- After the loop finishes, the sum of natural numbers is displayed using
printf()
.
- After the loop finishes, the sum of natural numbers is displayed using
Program Output
Example 1:
Enter a positive integer: 5
Sum of natural numbers from 1 to 5 is: 15
Explanation: The sum of numbers 1 + 2 + 3 + 4 + 5 = 15.
Example 2:
Enter a positive integer: 10
Sum of natural numbers from 1 to 10 is: 55
Explanation: The sum of numbers 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.
How the Program Works:
- User enters a positive integer (like 5 or 10).
- The
for
loop runs from 1 to the entered number. - In each iteration, the loop adds the current number (
i
) tosum
. - Finally, the program prints the total sum.
This program works for any valid positive integer input.
Last updated on