w3resource
C# Sharp Programming Exercises

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

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 - ......].

Sample Solution:-

C# Sharp Code:

using System;  
public class Exercise24  
{  
    public static void Main()
{
	double x,sum,no_row,ctr;
	int i,n;
	
	Console.Write("\n\n");
    Console.Write("Calculate the sum of the series [ x - x^3 + x^5 - ......]:\n");
    Console.Write("------------------------------------------------------------");
    Console.Write("\n\n");  	
	
	Console.Write("Input the value of x :");
    x= Convert.ToInt32(Console.ReadLine());  	
	Console.Write("Input number of terms : ");
    n= Convert.ToInt32(Console.ReadLine());  	
	sum =x; no_row = x;
	for (i=1;i<n;i++)
	{
	  ctr = (2*i)*(2*i+1);
	  no_row = -no_row*x*x/ctr;
	  sum =sum+ no_row;
	}
	Console.Write("\nThe sum = {0}\nNumber of terms = {1}\n The value of x = {2}\n",sum,n,x);
	}
}

Sample Output:

Calculate the sum of the series [ x - x^3 + x^5 - ......]:                                                                                                     
------------------------------------------------------------                                                                                                         
Input the value of x :7                                                                                                         
Input number of terms : 5                                                                                                         
The sum = 37.6940007716049                                                                                                         
Number of terms = 5                                                                                                         
 The value of x = 7 
 

Flowchart:

Flowchart: Calculate the sum of the series [ x - x^3 + x^5 + ......]

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to display the sum of the series [ 1+x+x^2/2!+x^3/3!+....].
Next: Write a program in C# Sharp to display the n terms of square natural number and their sum.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming