Print Sum of Series 1/1^2 + 1/2^2 + 1/3^2 …………1/n^2 in Java.



import java.util.Scanner;
public class Series 
{
 public static void main(String[] args) 
 {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter the no of terms ");
  int n = sc.nextInt();
  double sum = 0;
  for (int i = 1; i <= n; i++)
   sum = sum + (double) 1 / Math.pow(i, 2);
  System.out.println("Sum of series = " + sum);
 }
}

Output:
Enter the no of terms 
5
Sum of series = 1.4636111111111112
BUILD SUCCESSFUL (total time: 2 seconds)



No comments:

Post a Comment