This blog is under construction

Friday 12 July 2013

C program to generate Arithmetic progression(AP) series and find its sum

Write a C program to generate AP series and find its sum.
AP series is a series of numbers in which the difference between the consecutive elements is same.

Example: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19

Here, the common difference is 2.

And the sum of the AP series can be found by using the below formula.

Sum = n * (a1 + an)/2  => (10 * (1 + 19)) / 10 = 100

n is the number of elements in the AP series.
a1 is the first element in the AP series.
an is the last element in the AP series.


  #include <stdio.h>
  #include <stdlib.h>

  int main() {
        int i, n, *data, diff, sum, value = 1;

        /* get the number of elements in AP series */
        printf("Enter the value for number of elements:");
        scanf("%d", &n);

        /* get the common difference from the user */
        printf("Common difference for AP series:");
        scanf("%d", &diff);

        /* allocate memory to store the elements in AP series */
        data = (int *)malloc(sizeof(int) * n);

        /* print the series and store the AP series in data array */
        printf("AP series: ");
        for (i = 0; i < n; i++) {
                printf("%d ", value);
                data[i] = value;
                value = value + diff;
        }

        /* find the sum of the given AP series */
        sum = (n * (data[0] + data[n - 1]))/2;

        /* print the result */
        printf("\nSum of the AP series is %d\n", sum);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for number of elements:10
  Common difference for AP series:2
  AP series: 1 3 5 7 9 11 13 15 17 19 
  Sum of the AP series is 100



No comments:

Post a Comment