Enter value of x (in degrees): 60 Enter number of terms: 5
Value of cos(x) using series = 0.5
import java.util.Scanner;
public class CosineSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter value of x (in degrees): ");
double x = sc.nextDouble();
System.out.print("Enter number of terms: ");
int n = sc.nextInt();
// Convert degrees to radians
x = Math.toRadians(x);
double sum = 0;
double term;
for (int i = 0; i < n; i++) {
term = Math.pow(-1, i) * Math.pow(x, 2 * i) / factorial(2 * i);
sum += term;
}
System.out.println("Value of cos(x) using series = " + sum);
sc.close();
}
// Method to calculate factorial
public static long factorial(int num) {
long fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}
}
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.