Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Iterative Constructs in Java

Chapter 9

Iterative Constructs in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Program to Calculate the Value of Pi Using Series


19. Write a program to calculate the value of Pi with the help of the following series:
Pi = (4/1) - (4/3) + (4/5) - (4/7) + (4/9) - (4/11) + (4/13) - (4/15) ...
Hint: Use while loop with 100000 iterations.


Program Title: Program to Calculate the Value of Pi Using Series

Series Used

\[ \frac{4}{1} - \frac{4}{3} + \frac{4}{5} - \frac{4}{7} + \frac{4}{9} - \frac{4}{11} + \frac{4}{13} - \frac{4}{15} + \cdots \]

import java.util.Scanner;

 

class CalculatePi

{

    public static void main(String args[])

    {

        int i = 1, sign = 1;

        double pi = 0.0;

 

        while (i <= 100000 * 2)

        {

            pi = pi + (sign * 4.0 / i);

            sign = sign * (-1);   // Change sign

            i = i + 2;            // Next odd number

        }

 

        System.out.println("Value of Pi after 100000 iterations = " + pi);

    }

}

Output

Sample Output
Value of Pi after 100000 iterations = 3.1415826535897198 

📝 Explanation

  1. The program uses the Leibniz series to approximate the value of π.
  2. Variable i starts from 1 and increases by 2 to generate odd numbers.
  3. Variable sign alternates between +1 and −1 to handle addition and subtraction.
  4. The loop runs 100000 iterations using a while loop as instructed.
  5. Each term of the series is calculated as:
  1. sign * 4 / i
  2. The final value stored in pi is printed.