IT Developer

Nested for Loops in Java

Chapter 10

Nested for Loops in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Java Program to Compute sin x and cos x Using Power Series


11. Write a program that computes sin x and cos x by using the following power series:

sin x = x - x3/3! + x5/5! - x7/7! + ......

cos x = 1 - x2/2! + x4/4! - x6/6! + ......

Java Program : sin x and cos x Using Power Series

import java.util.Scanner;

 

public class SinCosSeries

{

    // Method to calculate factorial

    public static long factorial(int n)

    {

        long fact = 1;

        for(int i = 1; i <= n; i++)

        {

            fact *= i;

        }

        return fact;

    }

 

    public static void main(String[] args)

    {

        Scanner sc = new Scanner(System.in);

 

        System.out.println("Enter value of x (in radians):");

        double x = sc.nextDouble();

 

        System.out.println("Enter number of terms:");

        int n = sc.nextInt();

 

        double sinx = 0;

        double cosx = 0;

        int sign = 1;

 

        // Computing sin x

        for(int i = 1, count = 1; count <= n; i += 2, count++)

        {

            sinx += sign * (Math.pow(x, i) / factorial(i));

            sign *= -1;

        }

 

        sign = 1;

 

        // Computing cos x

        for(int i = 0, count = 1; count <= n; i += 2, count++)

        {

            cosx += sign * (Math.pow(x, i) / factorial(i));

            sign *= -1;

        }

 

        System.out.println("sin x = " + sinx);

        System.out.println("cos x = " + cosx);

 

        sc.close();

    }

}

Output

Sample Output 1 : 
 

📝 Explanation

For sin x:

\[ x - \frac{x^{3}}{3!} + \frac{x^{5}}{5!} - \frac{x^{7}}{7!} + \cdots \]

  • Powers increase by 2
  • Factorial of power
  • Signs alternate (+, −)

For cos x:

\[ 1 - \frac{x^{2}}{2!} + \frac{x^{4}}{4!} - \frac{x^{6}}{6!} + \cdots \]

  • Starts from 0 power
  • Same alternating sign logic