C Program to Calculate the Sum of Natural Numbers

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:

  1. Variable Declaration:

    • int n, sum = 0;: We declare two integer variables. n will hold the number input by the user, and sum will store the cumulative sum of natural numbers.
  2. Input:

    • The program prompts the user to enter a positive integer. This input is stored in the variable n using scanf().
  3. Logic:

    • A for loop starts at i = 1 and runs until i is less than or equal to n. In each iteration, the loop adds the value of i to the sum variable.
  4. Output:

    • After the loop finishes, the sum of natural numbers is displayed using printf().

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:

  1. User enters a positive integer (like 5 or 10).
  2. The for loop runs from 1 to the entered number.
  3. In each iteration, the loop adds the current number (i) to sum.
  4. Finally, the program prints the total sum.

This program works for any valid positive integer input.

Last updated on