C Program for Sum of First N Natural Numbers

The program adds first N natural numbers (starts from 1) and prints the sum in the console.

We wrote this program using Dev C++ version 4.9.9.2 on a Windows 7 64-bit system.  You may try other standard C compilers to run the program with modifications.

Learn following c programming concepts before you attempt this example program.

Problem Definition

Natural numbers are all positive numbers greater than number 0 and it does not include the number zero.

For example

Natural numbers = 1, 2, 3, 4, 5 ...

This C program reads the value of number N which is natural number and then sum all other natural numbers up to number N start from 1. Suppose N = 10 then

Sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Flowchart – Sum of First N Natural Numbers

Flowchart - Sum of N Natural Numbers
Flowchart – Sum of N Natural Numbers

Program Code – Sum of First N Natural Numbers

/* Program for sum of First N Natural Numbers */

#include <stdio.h>

#include <stdlib.h>

main()
{

    int num,i,sum;

    sum = 0;

/* read the number */

    printf("Enter number to sum:");

    scanf("%d",&num);

    for(i=1;i<=num;i++)
    {

        sum = sum + i;

    }

    printf("sum of %d number is %d\n",num,sum);

    getch();

    return 0;

}

The most important piece of code in the above example is the for loop.

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

The for loop starts from 1 and goes through each digit between 1 and num because variable i is incremented with each iteration ( i++) .  The value of num is user input and it can be a large number.

The value of i is added to variable sum using following statement. The value of sum also increments with each iteration of variable i in the for loop.

sum = sum + i;

The final value of sum is printed as output.

Output

Output - Sum of N Natural Numbers
Output – Sum of N Natural Numbers

Related Articles:

Advertisements