C++ Exercises: Display the sum of the specified series
23. Sum of the Series [9 + 99 + 999 + ...]
Write a program in C++ to display the sum of the series [ 9 + 99 + 999 + 9999 ...].
Visual Presentation:

Sample Solution:-
C++ Code :
#include <iostream> // Including input-output stream header
using namespace std; // Using standard namespace to avoid writing std::
int main() // Start of the main function
{
long int n, i, t = 9; // Declaration of long integer variables 'n' (number of terms), 'i' (loop counter), 't' (initial value of 9)
int sum = 0; // Declaration of integer variable 'sum' initialized to 0 (to store the sum)
cout << "\n\n Display the sum of the series [ 9 + 99 + 999 + 9999 ...]\n"; // Displaying a message on the console
cout << "-------------------------------------------------------------\n";
cout << " Input number of terms: "; // Prompting the user to input the number of terms
cin >> n; // Reading the input value as the number of terms
for (i = 1; i <= n; i++) // Loop to calculate 'n' terms of the series
{
sum += t; // Adding 't' (current term) to the sum
cout << t << " "; // Displaying the current term of the series
t = t * 10 + 9; // Generating the next term of the series by multiplying 't' by 10 and adding 9
}
cout << "\n The sum of the series = " << sum << endl; // Displaying the sum of the series
}
Sample Output:
Display the sum of the series [ 9 + 99 + 999 + 9999 ...] ------------------------------------------------------------- Input number of terms: 5 9 99 999 9999 99999 The sum of the sarise = 111105
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to generate the series 9, 99, 999, ... for n terms and compute their sum.
- Write a C++ program that constructs numbers of repeated 9's and adds them together, printing each term.
- Write a C++ program to display a series where each term is formed by appending a 9 to the previous term, then output the total sum.
- Write a C++ program that reads n and prints the series of numbers consisting of n repetitions of 9, followed by the sum of these numbers.
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C++ to display the n terms of harmonic series and their sum.
Next: Write a program in C++ to display the sum of the series [ 1+x+x^2/2!+x^3/3!+....].
What is the difficulty level of this exercise?