Problem Statement:
To Compute the Sine and Cosine series.
Algorithm
1) Start.
2) Read x and n
3) Display the menu and read the choice.
4) If ch=1 go to step 5 else go to step 13.
5) Set rad = 3.14/180*x, s1=rad.
6) Repeat steps 7 to 11 for i=3 to n.
7) p = pow(rad,i).
8) f=f*(i-1)*i.
9) R=p/f.
10) s1= s1+ k*r.
11) k=k*(-1).
12) Print the value of the sine series.
13) If ch= 2 go to step 14 else go to step 22
14) Set rad = 3.14/180*x ,s2=1.0.
15) Repeat steps 16 to 20 for i=2 to n.
16) p = pow(rad,i).
17) f=f*(i-1)*i.
18) R=p/f.
19) s1= s1+ k*r.
20) k=k*(-1).
21) Print the value of the cosine series.
22) Stop.
Program
import java.io.DataInputStream; public class SinCos { public static void main(String args[]) { DataInputStream in=new DataInputStream(System.in); int n,k=-1,f=1,i,ch,t=0; double p,s=0,x,rad,r=0; try { System.out.println("Enter the values of x and n:"); x=Float.valueOf(in.readLine()).floatValue(); n=Integer.parseInt(in.readLine()); System.out.println("\n1.Sine Series \n2.Cosine Series"); System.out.println("Enter your choice : "); ch=Integer.parseInt(in.readLine()); rad=3.14/180*x; if(ch==1) { s=rad; for(i=3;i<n;i+=2) { p=Math.pow(rad,i); f=f*(i-1)*i; r=p/f; s=s+k*r; k=k*(-1); } System.out.println("Sin("+x+")="+s); } else if(ch==2) { s=1.0; for(i=2;i<n;i+=2) { p=Math.pow(rad,i); f=f*(i-1)*i; r=p/f; s=s+k*r; k=k*(-1); } System.out.println("Cos("+x+")="+s); } else System.out.println("Wrong Choice!"); } catch(Exception e) { System.out.println("Error : "+e); } } } |
Output
Enter the values of x and n:
60
30
1.Sine Series
2.Cosine Series
Enter your choice :
1
Sin(60.0)=0.8657598006133088
Enter the values of x and n:
45
30
1.Sine Series
2.Cosine Series
Enter your choice :
2
Cos(45.0)=0.7073882691676964