C++ Practice Questions – Calculate Function Value

Time Limit: 2s Memory Limit: 192MBProblem DescriptionCalculate the function value according to the following recursive formula.When x=1, f(x)=10; when x>1, f(x)=f(x-1)+2Input FormatInteger variable xOutput Formatf(x)Sample Input10Sample Output28Code(1) Recursive Version

#include <iostream>
using namespace std;
int f(int x) {    if (x == 1) {        return 10;    } else {        return f(x - 1) + 2;    }}
int main() {    int x;    cin >> x;    cout << f(x) << endl;    return 0;}

(2) Iterative Version

#include <iostream>
using namespace std;
int f(int x) {    int result = 10;    for (int i = 2; i <= x; i++) {        result += 2;    }    return result;}
int main() {    int x;    cin >> x;    cout << f(x) << endl;    return 0;}

Output ResultC++ Practice Questions - Calculate Function ValueProblem Analysis

The problem provides a recursively defined function:

  • When x = 1, f(x) = 10

  • When x > 1, f(x) = f(x-1) + 2

We need to calculate the function value corresponding to the given x.

Methodology

  1. Recursive Implementation: Directly implement the function according to the recursive definition.

  2. Iterative Implementation: An iterative approach can also be used to avoid excessive recursion depth.

Code Explanation

  1. Recursive Version:

  • Base case: When x=1, return 10.

  • Recursive case: When x>1, return f(x-1)+2.

  • Iterative Version:

    • Initialize result to 10 (corresponding to the case when x=1).

    • Loop from 2 to x, adding 2 each time.

    • Return the final result.

    Validation Example

    • Input: 10

    • Calculation Process:

      • f(10) = f(9) + 2

      • f(9) = f(8) + 2

      • f(2) = f(1) + 2 = 10 + 2 = 12

      • f(10) = 10 + 2 × 9 = 28

    • Output: 28

    Both methods can correctly calculate the function value; the recursive version is more intuitive, while the iterative version is more efficient and avoids recursion depth issues.

    C++ Practice Questions - Calculate Function Value

    C++ Basic Tutorial Collection

    C++ Practice Questions - Calculate Function ValueC++ Basic Materials

    1. C++ Output

    2. C++ Variables

    3. C++ Input

    4. C++ Expressions

    5. IF Statements

    6. IF Applications

    7. WHILE Loop Statements

    8. FOR Loop Statements

    9. Arrays

    10. One-Dimensional Arrays

    11. Two-Dimensional Arrays

    12. C++ Functions

    13. C++ File Operations – Writing Files

    If you find it interesting, just click on me

    C++ Practice Questions - Calculate Function ValueC++ Practice Questions - Calculate Function ValueC++ Practice Questions - Calculate Function ValueC++ Practice Questions - Calculate Function Value

    Leave a Comment