Exercise
Double, Approximation Of Pi
Objective
Write a C# program to calculate an approximation for PI using the expression:
pi/4 = 1/1 - 1/3 + 1/5 -1/7 + 1/9 - 1/11 + 1/13 ...
The user will indicate how many terms must be used, and the program will display all the results until that amount of terms.
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace to use basic classes like Console
class Program // Define the main class of the program
{
static void Main() // The entry point of the program
{
// Prompt the user for the number of terms
Console.Write("Enter the number of terms to approximate Pi: ");
int terms = int.Parse(Console.ReadLine()); // Read the user's input and convert it to an integer
double piApproximation = 0.0; // Variable to store the approximation of Pi
// Loop through each term, adding or subtracting based on the formula
for (int i = 0; i < terms; i++) // Loop through the number of terms
{
// Calculate the current denominator (odd numbers: 1, 3, 5, 7, 9, ...)
double denominator = 2 * i + 1;
// Use the formula to alternate adding and subtracting terms
if (i % 2 == 0) // If i is even, add the term
{
piApproximation += 1 / denominator;
}
else // If i is odd, subtract the term
{
piApproximation -= 1 / denominator;
}
// Display the current approximation of Pi (multiply by 4 to get the approximation of Pi)
Console.WriteLine($"After {i + 1} terms, approximation of Pi: {4 * piApproximation}");
}
}
}