How to Calculate the Sum of ( n ) Natural Numbers in C


Here’s a beginner-friendly blog post for calculating the sum of ( n ) natural numbers in C.

Introduction
In programming, finding the sum of the first ( n ) natural numbers is a common task, especially when learning the basics of loops and arithmetic operations. In this blog, we’ll walk through a simple program in C that calculates the sum of ( n ) natural numbers using both a loop and a formula.


Understanding the Sum of ( n ) Natural Numbers

Sum = n ×(n+1) / 2

Method 1: Using a Loop

The first approach uses a loop to add each number from 1 up to ( n ).

Code

#include <stdio.h>

int main() {
    int n, sum = 0;

    // Asking the user for input
    printf("Enter a positive integer: ");
    scanf("%d", &n);

    // Calculating sum using a loop
    for(int i = 1; i <= n; i++) {
        sum += i;
    }

    // Displaying the result
    printf("Sum of the first %d natural numbers is: %d\n", n, sum);

    return 0;
}

Explanation

  1. We declare an integer variable n for the number up to which we want to find the sum.
  2. The sum variable is initialized to 0.
  3. A for loop iterates from 1 to ( n ), adding each value of i to sum.
  4. Finally, we display the result.

Example Output

Enter a positive integer: 5
Sum of the first 5 natural numbers is: 15

Method 2: Using the Formula

This method calculates the sum of ( n ) natural numbers directly with the formula:

Code

#include <stdio.h>

int main() {
    int n, sum;

    // Asking the user for input
    printf("Enter a positive integer: ");
    scanf("%d", &n);

    // Calculating sum using the formula
    sum = n * (n + 1) / 2;

    // Displaying the result
    printf("Sum of the first %d natural numbers is: %d\n", n, sum);

    return 0;
}

Explanation

  1. We take an integer input n.
  2. Using the formula n * (n + 1) / 2, we calculate the sum in a single line.
  3. The result is then printed.

Example Output

Enter a positive integer: 10
Sum of the first 10 natural numbers is: 55

Conclusion

Both methods are useful, and each has its benefits. The loop-based method helps understand basic loops and can be extended to other types of summations, while the formula-based method is efficient and concise. Try running both approaches and see how they work with different values of ( n )!

Happy Coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top