﻿ C# - Calculate the sum of the series x - x^3 + x^5 - x^7…

# C#: Calculate the sum of the series [ x - x^3 + x^5 - x^7 + x^9 -.....]

## C# Sharp For Loop: Exercise-24 with Solution

Write a program in C# Sharp to find the sum of the series [ x - x^3 + x^5 - x^7 + x^9 - ........].

Sample Solution:-

C# Sharp Code:

``````using System;  // Importing necessary namespace

public class Exercise24  // Declaration of the Exercise24 class
{
public static void Main()  // Main method, entry point of the program
{
double x, sum, ctr, p, term;  // Declaration of variables x, sum, ctr, p, term as double
int i, n;  // Declaration of variables i and n as integers

Console.Write("\n\n");  // Displaying new lines
Console.Write("Calculate the sum of the series [ x - x^3 + x^5 - x^7 + x^9 - .....]:\n");  // Displaying the purpose of the program
Console.Write("------------------------------------------------------------");  // Displaying a separator
Console.Write("\n\n");

Console.Write("Input the value of x :");  // Prompting the user to input the value of x
x = Convert.ToInt32(Console.ReadLine());  // Reading the value of x entered by the user

Console.Write("Input number of terms : ");  // Prompting the user to input the number of terms
n = Convert.ToInt32(Console.ReadLine());  // Reading the number of terms entered by the user

term = 1;  // Initializing term with 1
sum = 0;   // Initializing sum with 0

// Loop to calculate the sum of the series
for (i = 1, p = 1; i < n + 1; i++)
{
ctr = Math.Pow(x, p);  // Calculating x raised to the power p
sum = sum + ctr * term;  // Adding the current term to the sum
term = term * (-1);  // Changing the sign of the term for the next iteration
p = p + 2;  // Increasing power by 2 for the next iteration
}

// Displaying the result
Console.Write("\nThe sum = {0}\nNumber of terms = {1}\nThe value of x = {2}\n", sum, n, x);
}
}
```
```

Sample Output:

```Calculate the sum of the series [ x - x^3 + x^5 - x^7 + x^9 - .....]:
------------------------------------------------------------

Input the value of x :Input number of terms :
The sum = 410
Number of terms = 5
The value of x = 2
```

Flowchart:

C# Sharp Code Editor: