Search This Blog

Showing posts with label geometric progression. Show all posts
Showing posts with label geometric progression. Show all posts

Java Program to Display First N Terms of Geometric Progression

This post contains java program to display first n terms of a GP (geometric progression). Generally the following equation to find nth term of geometric progression is used.

Nth term of GP =  a * r(n-1)
Using a loop we will display each term until we reach nth term. But here since we use a loop, for the program it is enough to keep on multiplying with the common ratio. We need not to use the above equation each time. The java program to display first n terms of a geometric progression (GP) is as follows:

import java.util.Scanner;

public class GPTerms {
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.print("\n"+a);
    for(int i=1;i<n;i++)
        System.out.print(" "+(a*=r));
    }
}