Home / Programs / C program to find the sum of first n natural numbers.
Programming Example

C program to find the sum of first n natural numbers.

👁 5,849 Views
💻 Practical Program
📘 Step by Step Learning
C program to find the sum of first n natural numbers: This program prints the sum of first n natural numbers. A number is asked from the user and stored in variable n. For loop is used to add numbers

Program Code

#include<stdio.h>
int main()
{
    int i,n,s=0;
    printf("Enter value of n:");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        s=s+i;
    }
    printf("Sum = %d \n",s);
    return 0;
}

Output

Enter value of n:10
Sum = 55
Press any key to continue . . .

Explanation

This program prints the sum of first n natural numbers. A number is asked from the user and stored in variable n. For loop is used to add numbers from 1 to n and store the sum in s. Variable i is used for looping and it is incremented on each iteration. The condition is checked and until i is less than or equal to n, the loop runs. Finally the value of sum is printed after terminating the loop.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.