Write a java program to compute cosine series.

Java Programming Language Decision Making in java (Article) Decision Making in java (Program)

11

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:

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

Output:


                                                                     
                              

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.