Write a java program to print the sum of the following series based on
user's choice:
S 1/12 + 1/2^2 + 1/3^2.. 1/n^2
S 1/1 1/2 + 1/3 1/4...l/n
Answers
Answer:
Program:-
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int ch,n;
double s=0.0;//Initialilsing here so that it can be used both times in the switch
System.out.println("Enter 1 for dispalying the sum of Series 1");
System.out.println("Enter 2 for displaying the sum of Series 2");
System.out.println("Enter your choice");
ch=in.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter the limit:");
n=in.nextInt();
for(int i=1;i<=n;i++)
{
s=s+1/(double)Math.pow(i,2);
}
System.out.println("The sum of the series:"+s);
break;
case 2:
System.out.println("Enter the limit:");
n=in.nextInt();
for(int i=1;i<=n;i++)
{
s=s+1/(double)i;
}
System.out.println("The sum of the series:"+s);
break;
default:
System.out.println("Invalid choice");
}
in.close();
}
}
Output is attached
- You may confirm by checking the answer by solving though I have checked