Programming Example
Write a java program to compute cosine series.
Study this program carefully to understand the logic, output, and explanation in a structured way.
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 read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.