nth term of AP = a + (n - 1) * d
where a is first term and d is common difference. 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 adding the common difference. We need not to use the above equation each time. The java program to display first n terms of a arithmetic progression (AP) is as follows:
public class APTerms { public static void main(String[] arg) { int a,d,n; Scanner sc = new Scanner(System.in); System.out.println("Enter first term, common difference and n (number of terms)"); a=sc.nextInt()-(d=sc.nextInt()); n=sc.nextInt(); for(int i=0;i<n;i++) System.out.print(" "+(a+=d)); } }
No comments:
Post a Comment