Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to compute geometric progression
In C programming, a geometric progression (GP) is a sequence where each term after the first is found by multiplying the previous term by a common ratio. The sum of a geometric progression follows the formula: 1 + x + x² + x³ + ... + x?.
Syntax
sum = 1 + x + x² + x³ + ... + x?
Algorithm
The algorithm to compute geometric progression is as follows −
- Read values for x (common ratio) and n (number of terms)
- Initialize sum to 0
- Use a loop to calculate sum = sum + pow(x, i) for i from 0 to n
- Display the result
Example
Following is the C program to compute the geometric progression −
#include <stdio.h>
#include <math.h>
int main() {
int x, n, i;
double sum = 0.0;
printf("Enter the values for x and n: ");
scanf("%d %d", &x, &n);
if (n >= 0) {
for (i = 0; i <= n; i++) {
sum = sum + pow(x, i);
}
printf("x = %d, n = %d<br>", x, n);
printf("The sum of the geometric progression is: %.0f<br>", sum);
} else {
printf("Not a valid n value: %d<br>", n);
}
return 0;
}
Enter the values for x and n: 4 5 x = 4, n = 5 The sum of the geometric progression is: 1365
Flowchart
Key Points
- The program uses
pow()function frommath.hto calculate powers - Loop runs from i = 0 to n (inclusive) to include all terms
- Input validation ensures n is non-negative
- Sum is calculated as: 1 + x¹ + x² + x³ + ... + x?
Conclusion
Computing geometric progression in C involves using a simple loop with the pow() function. This approach efficiently calculates the sum of all terms from x? to x? and provides a clear mathematical demonstration of geometric sequences.
Advertisements
