Turn Desktop View Off
by Dinesh Thakur

This program segment calculates the sum of integer numbers from 1 to n. Initially, the value of n is read from the keyboard and variable sum is initialized to zero. Then a for loop is set up in which the loop variable j assumes values from 1 to n. For each value of j, the assignment statement included in the for loop is executed and the value of j is added to the previous value of sum.

Thus, when the execution of the for loop is over, variable sum will contain the sum of numbers from 1 to n. Finally, the value of sum is printed on the screen. The program output is shown below: 


#include<stdio.h>
void main()
{
       int n,j,sum=0;
       clrscr();
       printf("Enter the Number : ");
       scanf("%d",&n);
       for(j=1;j<=n;j++)
           {
              printf("%d ",j);
              sum=sum+j;
           }
              printf("\nSum of  %d is : %d ",n,sum);
              getch();
}

Program to Sum of N Number