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 Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

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

                        
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

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.

🔥 Practice suggestion

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.