This blog is under construction

Saturday 13 July 2013

C program to generate Harmonic progression(HP) series

Write a C program to generate Harmonic progression series.

The general form of HP series is a, a/(1 + d), a/(1 + 2d), a/(1 + 3d), ..., a/(1+ kd).


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

  int main() {
        int n, a, d, i, tmp = 1,  *data;

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

        /* get the first element */
        printf("Enter your first element:");
        scanf("%d", &a);

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

        /* allocate memory to store data */
        data = (int *)malloc(sizeof(int) * n);

        /* prints the harmonic series */
        for (i = 0; i < n; i++) {
                printf("%d/%d ", a, tmp);
                data[i] = (1.0 * a) / tmp;
                tmp = 1 + ((i + 1) * d);
        }

        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements:10
  Enter your first element:12
  Enter the value for d:1
  12/1 12/2 12/3 12/4 12/5 12/6 12/7 12/8 12/9 12/10 



No comments:

Post a Comment