This blog is under construction

Monday, 10 June 2013

C program to find the sum of series: 1 + (1 + 2) +..+ (1 + 2 +..+ N)

Write a C program to find the sum of series 
1 + (1 + 2) + (1 + 2 + 3) + .. + (1 + 2 + 3 + .... + N).



  /* 
   *   C program to print sum of the series: 1 + (1 + 2) + 
   *    (1 + 2 + 3) + .. + (1 + 2 + 3 + .... + N)
   */
  #include <stdio.h>
  int main() {
        int i, j, n, sum = 0, val = 0;

        printf("Enter the value for n:");
        /* get the value of n from user */
        scanf("%d", &n);

        for (i = 1; i <= n; i++) {
                for (j = 1; j <= i; j++)
                        val = val + j;
                /* calculate sum of the series */
                sum = sum + val;
                val = 0;
        }

        /* print the result */
        printf("Output: %d\n", sum);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:5
  Output: 35



No comments:

Post a Comment