C Program to Find Sum of First N Natural Numbers

This program calculates the sum of the first N natural numbers entered by the user using a for loop or using the formula N*(N+1)/2.

Concept Overview

The sum of first N natural numbers can be calculated using the formula: Sum = N*(N+1)/2. Alternatively, a for loop can be used to iterate from 1 to N and add each number to a sum variable.

Program

C
#include <stdio.h>

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

    printf("Enter value of N: ");
    scanf("%d", &n);

    for(int i = 1; i <= n; i++) {
        sum += i;
    }

    printf("Sum of first %d natural numbers is %d\n", n, sum);

    return 0;
}

Output

Enter value of N: 5
Sum of first 5 natural numbers is 15

Explanation

  • `for(i = 1; i <= n; i++) sum += i;` – Loops through numbers from 1 to N and accumulates the sum.
  • `sum = n*(n+1)/2;` – Alternative formula method to find sum directly.
  • `printf()` – Displays the sum on the screen.
Note: Note: You can use either loop or formula method based on your preference. Formula is faster for large N.