ICSE Class 10 Computer Applications
Question 22 of 22
Nested for loops — Question 22
Back to all questions 22
Question Question 11
Write a program that computes sin x and cos x by using the following power series:
sin x = x - x3/3! + x5/5! - x7/7! + ......
cos x = 1 - x2/2! + x4/4! - x6/6! + ......
import java.util.Scanner;
public class KboatSeries
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter x: ");
int x = in.nextInt();
double sinx = 0, cosx = 0;
int a = 1;
for (int i = 1; i <= 20; i += 2) {
long f = 1;
for (int j = 1; j <= i; j++)
f *= j;
double t = Math.pow(x, i) / f * a;
sinx += t;
a *= -1;
}
a = 1;
for (int i = 0; i <= 20; i += 2) {
long f = 1;
for (int j = 1; j <= i; j++)
f *= j;
double t = Math.pow(x, i) / f * a;
cosx += t;
a *= -1;
}
System.out.println("Sin x = " + sinx);
System.out.println("Cos x = " + cosx);
}
}Output
