Search This Blog

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

Java Program to Find Sum of First N Terms of an Arithmetic Progression

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

sum of first n terms = (n / 2) * (2 * a + (n - 1) * d)
sum of first n terms of an arithmetic progression, equation to find sum of an ap,
Sum of first n terms of an AP (arithmetic progression)

Now, we will see a java program to find sum of first n terms of an AP. The java program is as follows:


import java.util.Scanner;

public class SumofAP {
public static void main(String[] arg)
    {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first term, common difference and n (number of terms)");
    int a=sc.nextInt(),d=sc.nextInt(),n=sc.nextInt();
    System.out.print("Sum: "+n*(2*a+(n-1)*d)/2);
    }
}


Java Program to Display First N Terms of an Arithmetic Progression

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

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));
    }
}