Thursday, 9 June 2016

Sum of natural numbers in a given range

This program finds the sum of natural numbers from start to end.
We calculate sum as per the below formula,
        tn = last term , a = 1st term , d = common diff , n = no of terms 

        tn = a + (n-1)d  

        Here d = 1

        n = tn - a + 1

        Sn = n * (a + tn)/2


Code

#include<stdio.h>

int main()
{
    int a,tn,Sn,n;

    printf("\n Enter start ");
    scanf("%d",&a);

    printf("\n Enter end ");
    scanf("%d",&tn);

    n = tn - a + 1;

    Sn = (n * (a + tn))/2;

    printf("\n Sum = %d",Sn);

    return 0;
}


O/P



No comments:

Post a Comment