Home / Programs / Write a java program to compute cosine series.
Programming Example

Write a java program to compute cosine series.

👁 16 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

Given Input:

Enter value of x (in degrees): 60
Enter number of terms: 5

Expected Output:

Value of cos(x) using series = 0.5

Program Code

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;
    }
}

How to learn from this program

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.