sum= a*(1-r^n)/(1-r)
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)); } }
No comments:
Post a Comment