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 ...].
This C program calculates and displays the sum of a series where each term is formed by repeating the digit 9 (e.g., 9, 99, 999, 9999, ...). The program prompts the user for the number of terms (n) and then computes the sum using a loop that generates each term and adds it to the total sum. The final sum is then printed to the console.
Visual Presentation:
Sample Solution:
C Code:
#include <stdio.h> // Include the standard input/output header file.
void 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.
}
Output:
Input the number or terms :5 9 99 999 9999 99999 The sum of the series = 111105
Flowchart:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming-exercises/for-loop/c-for-loop-exercises-21.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics