C Exercises: Display the sum of the series [ 9 + 99 + 999 + 9999 ...]
C For Loop: Exercise-21 with Solution
Write a program in C to display the sum of the series [ 9 + 99 + 999 + 9999 ...].
Visual Presentation:
![Display the sum of the series [ 9 + 99 + 999 + 9999 ...]](https://www.w3resource.com/w3r_images/c-for-loop-image-exercises-21.png)
Sample Solution:
C Code:
#include <stdio.h> // Include the standard input/output header file.
int main() {
long int n, i, t = 9; // Declare variables to store input, control loop indices, and temporary value.
int sum = 0; // Initialize a variable to store the sum.
printf("Input the number or terms :"); // Prompt the user for input.
scanf("%ld", &n); // Read the value of 'n' from the user.
for (i = 1; i <= n; i++) // Loop for the number of terms.
{
sum += t; // Add 't' to the sum.
printf("%ld ", t); // Print the current value of 't'.
t = t * 10 + 9; // Update 't' for the next iteration.
}
printf("\nThe sum of the series = %d \n", sum); // Print the sum of the series.
return 0; // Return 0 to indicate successful execution.
}
Sample Output:
Input the number or terms :5 9 99 999 9999 99999 The sum of the series = 111105
Flowchart:
![Flowchart: Display the sum of the series [ 9 + 99 + 999 + 9999 ...]](https://www.w3resource.com/w3r_images/c-for-loop-exercises-21.png)
C Programming Code Editor:
Previous: Write a program in C to display the pattern like a pyramid using asterisk and each row contain an odd number of asterisks.
Next: Write a program in C to print the Floyd's Triangle.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join