Find Sum of First N Natural Numbers in C Language

To find the sum of first N Natural numbers in C language, we can use formula n * (n + 1) / 2 or use a looping statement to accumulate the sum from 1 to n.

In this tutorial, we will go through the programs using formula, and each of the looping statements.

Find Sum using Formula

In the following program, we read an integer from user into variable n, and then we use the formula n * (n + 1) / 2 to find the sum of first n natural numbers .

main.c

</>
Copy
#include <stdio.h>

int main() {
    int n, sum;
    
    printf("Enter a number : ");
    scanf("%d", &n);
    
    sum = (n * (n + 1)) / 2;
    printf("Sum : %d\n", sum);
    
    return 0;
}

Output

Enter a number : 4
Sum : 10
Program ended with exit code: 0

Output

Enter a number : 100
Sum : 5050
Program ended with exit code: 0

Find Sum using For Loop

In the following program, we read an integer from user into variable n, write a For Loop to iterate from 1 to n, and in the For Loop, we accumulate the sum in variable sum.

Refer C For Loop tutorial.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int n, sum = 0;
    
    printf("Enter a number : ");
    scanf("%d", &n);
    
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    printf("Sum : %d\n", sum);
    
    return 0;
}

Output

Enter a number : 5
Sum : 15
Program ended with exit code: 0

Find Sum using While Loop

In the following program, we read an integer from user into variable n, write a While Loop to iterate from 1 to n, and in the While Loop, we accumulate the sum in variable sum.

Refer C While Loop tutorial.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int n, sum = 0;
    
    printf("Enter a number : ");
    scanf("%d", &n);
    
    int i = 1;
    while (i <= n) {
        sum += i;
        i++;
    }
    printf("Sum : %d\n", sum);
    
    return 0;
}

Output

Enter a number : 5
Sum : 15
Program ended with exit code: 0

Find Sum using Do-While Loop

In the following program, we read an integer from user into variable n, write a Do-While Loop to iterate from 1 to n, and in this Do-While Loop, we accumulate the sum in variable sum.

Refer C Do-While Loop tutorial.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int n, sum = 0;
    
    printf("Enter a number : ");
    scanf("%d", &n);
    
    int i = 1;
    do {
        sum += i;
        i++;
    } while (i <= n);
    printf("Sum : %d\n", sum);
    
    return 0;
}

Output

Enter a number : 5
Sum : 15
Program ended with exit code: 0

Conclusion

In this C Tutorial, we learned how to find the sum of first N natural numbers in C language, in different ways, with examples.