Having some trouble, need help: Create a program that will do one of two functio
ID: 3840893 • Letter: H
Question
Having some trouble, need help:
Create a program that will do one of two functions using a menu, like so in c++
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
In C++, 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.
Explanation / Answer
#include <iostream>
using namespace std;
int catalan(int n)
{
unsigned long int cat[n+1];
cat[0]=cat[1]=1;
int i,j;
for(i=2;i<=n;i++)
{
cat[i]=0;
for(j=0;j<i;j++)
{
cat[i]+=cat[j]*cat[i-j-1]; //calatlon number
}
}
return cat[n];
}
int fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n-1)+fibonacci(n-2);//recursive calls
}
int main()
{
int option,n;
do
{
cout<<" 1. Do Catalan numbers";
cout<<" 2. Do Fibonacci numbers (recursive)";
cout<<" 0. Quit";
cout<<" Enter selection: ";
cin>>option;
switch(option)
{
case 1: cout<<" Enter Catalan number to calculate: ";
cin>>n;
cout<<" Catalan number at "<<n <<" is "<<catalan(n);
break;
case 2: cout<<" Enter Fibonacci number to calculate: ";
cin>>n;
cout<<" Fibonacci number "<<n <<" is "<<fibonacci(n);
break;
case 0: break;
default: cout<<" Invaid option";
break;
}
}while(option != 0);
return 0;
}
Output:
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
1. Do Catalan numbers
2. Do Fibonacci numbers (recursive)
0. Quit
Enter selection: 0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.