Search This Blog

Showing posts with label sum. Show all posts
Showing posts with label sum. 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);
    }
}