Write a C program to generate GP series and find its sum.
General form of GP series is a, ar, ar^2, ar^3, ar^4, ar^5 ...
a - First element of the sequence.
r - common ratio.
a = 2 and r = 5 GP series corresponds to these values are below.
2, 10, 50, 250 ....
Sum = a(1 - r^n)/(1 - r). Where n is the number of elements in the series.
Sum = 2(1 - 5^4)/ (1 - 5) = 312 <=> 2 + 10 + 50 + 250
General form of GP series is a, ar, ar^2, ar^3, ar^4, ar^5 ...
a - First element of the sequence.
r - common ratio.
a = 2 and r = 5 GP series corresponds to these values are below.
2, 10, 50, 250 ....
Sum = a(1 - r^n)/(1 - r). Where n is the number of elements in the series.
Sum = 2(1 - 5^4)/ (1 - 5) = 312 <=> 2 + 10 + 50 + 250
#include <stdlib.h>
#include <math.h>
int main() {
int *data, value, ratio, sum, tmp, i, j, n;
/* get the elements in series from user */
printf("Enter the number of elements:");
scanf("%d", &n);
/* get first element of GP series from user */
printf("1st Element in Geomentric Sequence:");
scanf("%d", &value);
/* get the ratio value from user */
printf("Enter the value for ratio:");
scanf("%d", &ratio);
tmp = value;
/* allocate memory to store values in GP series */
data = (int *)malloc(sizeof(int) * n);
/* stores the values of GP series in data array */
for (i = 0; i < n; i++) {
data[i] = tmp;
printf("%d ", data[i]);
tmp = value * pow(ratio, i + 1);
}
/* find the sum of the elements in GP series */
sum = (value * (1 - pow(ratio, n)))/ (1 - ratio);
/* print the results */
printf("\nSum of the elements in GP series is %d\n", sum);
return 0;
}
Note:
gcc gpSeries.c -lm => link math library since we have used math function pow().
Output:
jp@jp-VirtualBox:~/$ gcc gpSeries.c -lm
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of elements:4
1st Element in Geomentric Sequence:2
Enter the value for ratio:5
2 10 50 250
Sum of the elements in GP series is 312
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of elements:4
1st Element in Geomentric Sequence:2
Enter the value for ratio:5
2 10 50 250
Sum of the elements in GP series is 312
No comments:
Post a Comment