Search This Blog

Showing posts with label find sum of gp. Show all posts
Showing posts with label find sum of gp. Show all posts

Java Program to Find Sum of First N Terms of Geometric Progression

In this post we will see a java program to calculate sum of first n terms of a geometric progression. Geometric progression is also called GP (short for Geometric progression). The equation to find sum of first n terms of a geometric progression is as follows:

sum= a*(1-r^n)/(1-r)
sum of geometric progression, sum of gp, gp sum
sum of first n terms of geometric progression

Now, we will see a java program to find sum of first n terms of a GP. There is a case in which the above equation fails. When r (common ratio) is 1, the above equation won't work. Then every term in the GP will be same as first term. Therefore, in that case, the sum is a*n. The program is as follows:



import java.util.Scanner;

public class SumGP {
public static void main(String[] arg)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter first term, common ratio and n (number of terms)");
    int a=sc.nextInt(),r=sc.nextInt(),n=sc.nextInt();
        System.out.println((r==1)?"Sum is:"+a*n:"Sum is:"+(float)a*(1-Math.pow(r,n))/(1-r));
    }
}