Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please use c++, cpp write this code. Recursion Vs Iteration, Fibonacci series us

ID: 3923633 • Letter: P

Question

Please use c++, cpp write this code.

Recursion Vs Iteration, Fibonacci series using Recursion, Write a Code to generate Factorial using Recursion.

#include <iostream>

using namespace std;

/*

    To get the lowdown on recursion and recursive functions, please see C++ Recursion Example 1 (Understanding the Basics)

    Let's now experiment with the Fibonacci sequence.

    A Fibonacci sequence is a mathematical phenomena that commonly occurs in nature. The mathematical expression is as so: F(n) = F(n-1) + F(n-2)

    This is an example of a problem that maps very naturally to recursive functions; even the mathematical expression is recursive!

*/

int fib(int num)

{

cout << "Finding the fib of " << num << endl;

//The rules of Fibonacii states that F0 = 0 and F1 = 1.

//These are our termination cases.

if(num == 0)

{

cout << "We have reached the termination case of 0. Returning 0" << endl;

return 0;

}

if(num == 1)

{

cout << "We have reached the termination case of 1. Returning 1" << endl;

return 1;

}

int result = fib(num - 1) + fib(num - 2);

cout << "Fib of " << num << " is " << result << endl;

return result;

}

int main()

{

fib(6);

return 0;

}

Explanation / Answer

// C++ factorial using recursion
#include <iostream>

using namespace std;

int Factorial(int inputNumber)
{
    int result;
    cout << "Finding factorial of " << inputNumber << endl;

    if (inputNumber >= 1)
    {
        result = inputNumber*Factorial(inputNumber-1);
        cout << "factorial of " << inputNumber << " is " << result << endl;
        return result;
    }
    else
    {
        cout << "We have reached the termination case of 1. Returning 1" << endl;
        return 1;
    }
}

int main()
{
    int inputNumber;
    cout <<"Enter an integer: ";;
    cin >> inputNumber;
    cout <<" Factorial of " << inputNumber << " = " << Factorial(inputNumber) << endl;
    return 0;
}


/*
output:

Enter an integer: 6

Finding factorial of 6
Finding factorial of 5
Finding factorial of 4
Finding factorial of 3
Finding factorial of 2
Finding factorial of 1
Finding factorial of 0
We have reached the termination case of 1. Returning 1
factorial of 1 is 1
factorial of 2 is 2
factorial of 3 is 6
factorial of 4 is 24
factorial of 5 is 120
factorial of 6 is 720

Factorial of 6 = 720

*/