Starting from:

$29.99

Lab 12: Recursion 2

CS 2401 
Lab 12: Recursion 2

For this lab you are to write two recursive functions. The two problems have nothing to do with each
other, so you should do the easy one first and test it, and then tackle the second one. The functions are
to be recursive, meaning that there will be no “while” or “for” anywhere in the program except where I
have shown it in the main below. (No credit given for a non-recursive solutions.)
Problem One: Write a recursive function that takes a decimal number and outputs the number in another
format according to users’ input. For example, the user could choose to convert the decimal number into a
binary number. This is accomplished by repeated division by two. Hint: The trick is that the least significant
digit is the first one you compute, so it needs to be done recursively.
Run with the function with bases 2, 3, and 7.
The main for this program will look like this:
#include <iostream>
using namespace std;
void convert_to_base(int n, int base);
int main(){
int num;
cout << "Please input an int decimal number: ";
cin >> num;
cout << "\nThis number in base 2 is: ";
convert_to_base(num, 2); // shows the number to base 2
cout << "\nThis number in base 3 is: ";
convert_to_base(num, 3); // shows the number to base 3
cout << "\nThis number in base 7 is: ";
convert_to_base(num, 7);
}
A sample output:
Please input an int decimal number: 30
This number in base 2 is: 11110
This number in base 3 is: 1010
This number in base 7 is: 42
Problem Two: In this one, the recursive function takes a string and two arguments that are array
indexes. The program then reverses all the characters within the array indexes, so given s= “abcdef” and
the numbers 2 and 5 the printed string should be “abfedc”. Remember to pass the string by reference
and that the base case needs to consider the possibility of the two indexes crossing each other:
Here’s what the main will look like:
#include <iostream>
#include <string>
using namespace std;
reversing(string s, int start, int end);
int main(){
 string s;
 int start, end;
 cout << "Enter a string: ";
 getline(cin,s);
 cout << "Enter two numbers that are within the bounds of the string.\n";
 cin >> start >> end;
 cout << "This is how your string looks now:\n";
 reversing(s, start, end);
 cout << s << endl;
 return 0;
}
And a sample output:
Enter a string: go bobcats
Enter two numbers that are within the bounds of the string.
3 7
This is how your string looks now:
go acbobts
Submit your source code, showing both of the recursive functions and the main that calls them, and the
script file that shows a complete running of the program to Blackboard.

More products