The sum of n terms of AP is the sum(addition) of the first n terms of the arithmetic sequence. It is equal to n divided by 2 times the sum of twice the first term – 'a' and the product of the difference between second and first term-'d' also known as common difference, and (n-1), where n is a number of terms to be added.
The code for this problem is:
import java.util.Scanner;
public class SumofNtermsofAP {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first term of the AP: ");
int a = scanner.nextInt();
System.out.println("Enter common difference of the AP: ");
int cd = scanner.nextInt();
System.out.println("Enter the number of terms of the AP: ");
float n = scanner.nextInt();
float Sn = n/2*(2*a+(n-1)*cd);
System.out.println("The sum of "+n+ " terms of the AP is: "+Sn);
}
}
No comments:
Post a Comment