Java program to find out the sum of A.P. series



Arithmetic progression (A.P.):
A series of numbers in which difference of any two consecutive numbers is always a same number that is constant. This constant is called as common difference.

Example of A.P. series:
 3 + 8 + 13 + 18 + 23 + 28 + 33


package demo;
import java.util.Scanner;
public class Series {
 public static void main(String[] args)
 {
  Scanner sc = new Scanner(System.in);
  int a, d, n, tn;
  int sum = 0;

  System.out.print("Enter the first number of the A.P. series: ");
  a = sc.nextInt();

  System.out.print("Enter the total numbers in the A.P. series: ");
  n = sc.nextInt();

  System.out.print("Enter the common difference of A.P. series: ");
  d = sc.nextInt();

  sum = (n * (2 * a + (n - 1) * d)) / 2;
  tn = a + (n - 1) * d;
  System.out.print("Sum of the series A.P.: ");

  for (int i = a; i <= tn; i = i + d) 
  {
   if (i != tn) 
   {
    System.out.print(i + " + ");
   } else 
   {
    System.out.print(i + " = " + sum + " ");
   }
  }
 }
}

Output:

Enter the first number of the A.P. series: 3
Enter the total numbers in the A.P. series: 7
Enter the common difference of A.P. series: 5
Sum of the series A.P.: 3 + 8 + 13 + 18 + 23 + 28 + 33 = 126 
BUILD SUCCESSFUL (total time: 17 seconds)


1 comment:

  1. public class JavaApplication1 {

    public static void main(String[] args) {
    int n1,n2,i,gap;
    Scanner sc=new Scanner(System.in);
    n1=sc.nextInt();
    n2=sc.nextInt();
    int sum=0;
    gap=sc.nextInt();
    int temp=n1;
    System.out.print(temp);
    for(i=temp;i<=n2+1;i++)
    {
    n1=n1+gap;
    sum+=n1;
    System.out.print("+"+n1);
    }
    System.out.println(sum+temp);
    }

    }

    ReplyDelete