w3resource

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

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

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.



Follow us on Facebook and Twitter for latest update.