In: Computer Science
Please C++ create a program that will do one of two functions using a menu, like so: 1. Do Catalan numbers 2. Do Fibonacci numbers (recursive) 0. Quit Enter selection: 1 Enter Catalan number to calculate: 3 Catalan number at 3 is 5 1. Do Catalan numbers 2. Do Fibonacci numbers (recursive) 0. Quit Enter selection: 2 Enter Fibonacci number to calculate: 6 Fibonacci number 6 is 8 Create a function of catalan that will take a parameter and return the Catalan number. Also create a function of Fibonacci that will take a parameter, calculate using recursion the Fibonacci number and return the number. Main will have a do/while loop that will print the menu, enter the selection, and call the functions. Have it quit on 0. Fibonacci are the sequence 1 1 2 3 5 8 13 21 Catalan numbers follow the sequence defined in Chapter 5 of the text. Also, the formula for the Catalan sequence is given here: https://en.wikipedia.org/wiki/Catalan_number (Links to an external site.)
C++ program:
#include<iostream>
using namespace std;
// Function to find the catalan number
unsigned long int catalan(unsigned int n)
{
// Base case
if (n <= 1) return 1;
// catalan(n) is sum of catalan(i)*catalan(n-i-1)
unsigned long int res = 0;
for (int i=0; i<n; i++)
res += catalan(i)*catalan(n-i-1);
// Returning the calculated result
return res;
}
// Function to calculate the nth Fibonacci number
int fib(int n)
{
// base conditions at n=1 and n=0
if (n == 1)
return 1;
else if (n == 0)
return 0;
// recursive call for n-1 and n-2
return fib(n-1) + fib(n-2);
}
// main Function
int main()
{
// while loop till user presses 0 to quit
while (1)
{
// printing the menu for user
int choice;
cout<<"1. Do Catalan numbers "<<endl;
cout<<"2. Do Fibonacci numbers (recursive)"<<endl;
cout<<"0. Quit"<<endl;
cout<<"Enter selection: ";
// taking user choice
cin>>choice;
// if choice is 1 calculating Catalan number
if (choice==1)
{
int num;
cout<<"Enter Catalan number to calculate: ";
cin>>num;
cout<<"Catalan number at "<<num<<" is "<<catalan(num)<<endl;
}
// if choice is 2 calculating Fibonacci number
else if (choice==2)
{
int num;
cout<<"Enter Fibonacci number to calculate: ";
cin>>num;
cout<<"Fibonacci number "<<num<<" is "<<fib(num)<<endl;
}
// if choice is 0 ending the program
else
{
break;
}
}
return 0;
}
Screenshot of code for reference:
Screenshot of output: