Home » C Examples » C Program for Sum of First N Natural Numbers

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 a 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.

(adsbygoogle = window.adsbygoogle || []).push({}); </script

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag

(adsbygoogle = window.adsbygoogle || []).push({});