C#: Display the sum of the series [ 9 + 99 + 999 + 9999 ...]
Write a program in C# Sharp to display the sum of the series [ 9 + 99 + 999 + 9999 ...].
Sample Solution:-
C# Sharp Code:
using System; // Importing necessary namespace
public class Exercise21 // Declaration of the Exercise21 class
{
public static void Main() // Main method, entry point of the program
{
int n, i, t = 9; // Declaration of variables n, i, t with initialization
int sum = 0; // Variable to store the sum, initialized to 0
Console.Write("\n\n"); // Displaying new lines
Console.Write("Display the sum of the series [ 9 + 99 + 999 + 9999 ...]:\n"); // Displaying the purpose of the program
Console.Write("-----------------------------------------------------------"); // Displaying a separator
Console.Write("\n\n");
Console.Write("Input the number or terms :"); // Prompting the user to input the number of terms
n = Convert.ToInt32(Console.ReadLine()); // Reading the number of terms entered by the user
// Loop to generate the series and calculate the sum
for (i = 1; i <= n; i++)
{
sum += t; // Adding the current value of t to the sum
Console.Write("{0} ", t); // Displaying the current value of t
t = t * 10 + 9; // Generating the next value of t for the series
}
Console.Write("\nThe sum of the series = {0} \n", sum); // Displaying the sum of the series
}
}
Sample Output:
Display the sum of the series [ 9 + 99 + 999 + 9999 ...]: ----------------------------------------------------------- Input the number or terms :5 9 99 999 9999 99999 The sum of the saries = 111105
Flowchart:
C# Sharp Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C# Sharp to display the pattern like a pyramid using asterisk and each row contain an odd number of asterisks.
Next: Write a program in C# Sharp to print the Floyd's Triangle.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics