In: Computer Science
Write a C++ program that requires the user to type in an integer M and computes the function y(M) which is defined by y(0)=2, y(1)=1, y(m+1)=y(m)+2*y(m-1).
Solution:
#include<iostream>
using namespace std;
int y(int M)
{
if(M==0)
return 2;
else if(M==1)
return 1;
else
return y(M-1)-2*y(M-2);
}
int main()
{
int M,ans;
cout<<"Enter a value for M: ";
cin>>M;
ans=y(M);
cout<<"The value of y(m) = "<<ans<<endl;
return 0;
}
Output: