Midterm Exam
Do the following by using Recursion:
1. Create a code that can print any numbers depending on the inputted value of the user in ascending then reverse it in descending order.
Sample output:
Enter number: 5
1
2
3
4
5
4
3
2
1
2. Write a code that will identify if the inputted value is odd or even. If it is odd then get the sum of all the odd numbers prior to the inputted value, same goes if it is even then get the sum of all the even numbers.
Sample output:
Enter number: 9
Odd
The sum is: 25
3. Using the fibonacci sequence, create a code that will print the remainder using %5 of the sum of the 2 added value depending on the input term of the user.
Sample output:
Enter 1st term: 5
Enter 2nd term: 6
The sum is: 13
The remainder is: 3
1.
void printer(int n) {
if (n = 1) return;
std::cout << n << " ";
printer(n - 1);
std::cout << n << " ";
}
2.
int SumOddEven(int n)
{
if(n<=0)return 0;
return n+SumOddEven(n-2);
}
3.
int recursion(int n){
if(n < 2){
return n;
}
else {
return recursion(n-1) + recursion(n-2);
}
}
using namespace std;
int main(){
int term1,term2, sum;
cout<<"Enter 1st term"<<endl;
cin>>term1;
cout<<"Enter 2nd term"<<endl;
cin>>term2;
sum=recursion(term1)+recursion(term2);
cout<<"The sum is: "<<sum<<endl;
cout<<"The remainder is: "<<sum%5<<endl;
return 0;
}
Comments
Leave a comment