Sum of the series 1+2+3+4..........

Share it Please
This program is used to count or illustrate 1+2+3+4+5+6+7+8+.....................+n.This is the second method or second source code for this program.You can see other method at here.In this program i have three variables in this program they are a,n and ans.And ans=0 this is because ans=ans+a; if we have not set ans=0 then it will assign garbage value to ans therefore it will affect answer.Now let us see program to understand more.

Program:

#include<stdio.h>
#include<conio.h>
main()
{
    long n,ans=0,a;
    clrscr();
    printf("Enter number: ");
    scanf("%ld",&n);
    printf("\n");
    for(a=1;a<=n;a++)
    {
        ans=ans+a;
        if(a==n)
        {
            printf("%ld=",a);
        }
        else
        {
            printf("%ld+",a);
        }
    }
    printf("%ld\n\nSum till %ld number is %ld",ans,n,ans);
    getch();
}


Output:

Sum of the series 1+2+3+4.......... in c programming