Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program for sum of geometric series in C
Given three inputs first one is “a” which is for the first term of geometric series second is “r” which is the common ratio and “n” which are the number of series whose sum we have to find.
Geometric series is a series which have a constant ratio between its successive terms. Using the above stated inputs “a”, “r” and “n” we have to find the geometric series i.e., a, ar, ??2 , ??3 , ??4 , … and their sum, i.e., a + ar + ??2+ ??3 + ??4 +…
Input
a = 1 r = 0.5 n = 5
Output
1.937500
Input
a = 2 r = 2.0 n = 8
Output
510.000000
Approach used below is as follows to solve the problem
Take all the inputs a, r, n.
Calculate the sum of geometric series, adding the full series.
Algorithm
Start In function float sumgeometric(float a, float r, int n) Step 1→Declare and Initialize sum = 0 Step 2→ Loop For i = 0 and i < n and i++ Set sum = sum + a Set a = a * r Step 3→ Return sum In function int main() Step 1→ Declare and initialize a = 1 Step 2→ Declare and Initialize float r = 0.5 Step 3→ Declare and initialize n = 5 Step 4→ Print sumgeometric(a, r, n) Stop
Example
#include <stdio.h>
// function to calculate sum of
// geometric series
float sumgeometric(float a, float r, int n){
float sum = 0;
for (int i = 0; i < n; i++){
sum = sum + a;
a = a * r;
}
return sum;
}
int main(){
int a = 1; // first term
float r = 0.5; // their common ratio
int n = 5; // number of terms
printf("%f", sumgeometric(a, r, n));
return 0;
}
Output
If run the above code it will generate the following output −
1.937500
Advertisements