C Exercise Example 18

100 Classic C Examples

Title:Finds=a+aa+aaa+aaaa+aa...athe value of, whereais a number, for example2+22+222+2222+22222(At this point, a total of 5 numbers are added), the number of numbers to add is controlled by the keyboard.

Program analysis:The key is to calculate the value of each term.

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. // #include <stdio.h> int main() { int sum = 0; // variable to store the result int base, terms; // base is the value of a, terms is the value of n int temp; // temporary variable, used to calculate the value of the current term // prompt the user to enter values printf("Please enter integers a and n (e.g., 2 and 5):\n"); scanf("%d%d", &base, &terms); // initialize temp to a temp = base; // calculate a + aa + aaa + ... using a loop while (terms > 0) { sum += temp; // accumulate the current term base *= 10; // base shifts one digit to the left each time (e.g., 2 -> 20 -> 200) temp += base; // update temp to become the next term terms--; // decrement the remaining number of terms } // Output the results printf("The calculation result is: %d\n", sum); return 0; }

The output of the above example is:

请输入整数 a 和 n(例如 2 和 5):
2 5
计算结果为:24690

Implemented using recursion:

Example

#include <stdio.h>

// recursive function to calculate the value of each term
int calculate_term(int count, int base);

int main() {
    int count;  // Total number of terms
    int base;   // Initial value
    int sum = 0; // Accumulated result

    // Prompt the user to enter the initial value and the total number of terms
    printf("Please enter initial value (a):");
    scanf("%d", &base);

    printf("Please enter number of terms (n):");
    scanf("%d", &count);

    // Check the validity of the input
    if (count <= 0 || base <= 0) {
        printf("The input initial value and number of terms must be positive integers!"\n");
        return 1; // Return error status
    }

    // Accumulate each term through a loop
    for (int i = 1; i <= count; i++) {
        sum += calculate_term(i, base); // Call the recursive function to calculate the value of the i-th term
    }

    // Output the final result
    printf("The calculation result is: %d"\n", sum);
    return 0;
}

// Recursive function, calculate the value of the current term
int calculate_term(int count, int base) {
    if (count == 1) {
        return base; // Recursion termination condition: the first term directly returns base
    } else {
        // Recursive calculation: the current term equals the previous term multiplied by 10 plus base
        return calculate_term(count - 1, base) * 10 + base;
    }
}

The output of the above example is:

请输入初始值 (a):2
请输入项数 (n):5
计算结果为:24690

100 Classic C Examples

other extensions