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.

Advertisements

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\hspace{2mm} numbers = 1, 2, 3, 4, 5, \cdots

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

Advertisements
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 the following statement. The value of sum also increments with each iteration of the variable i in the for loop.

sum = sum + i;

The final value of the sum is printed as output.

Output

How many numbers to add?:10
------------------------
sum of 10 number is 55
------------------------

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.