C++ Startup
1. Write a function that takes two string objects, and returns true
if the second is a prefix of the first, and false otherwise. Your
function should not call find() or rfind(). Write a main function to
test your startsWith
function.
bool startsWith(string
s, string pre) {
2. Write a reverse()
function that takes a string, and returns a new string that is its
reverse. E.g.,
reverse("bark") should
return the string object representation of "krab". Write a main
function to test your reverse
function.
string reverse(string
s) {
3. Given the following statements:
string s = "abcde";
string t = "";
What is the value of:
a) t.length()
b) s.replace(0, 2,
'x') c) s[3] d) s.at(2)
e) s.substr(1)
f) s.substr(3, 8)
g) s.substr(1,
1)
What is the output?
t += 'A';
cout << t;
4. What's the output?
void mystery(int &
a, int & b, int c) {
c += a + b;
b += a + c;
a *= 2;
}
int main() {
int i = 1;
int j = 2;
int k = 3;
mystery(k, i, j);
cout << i << " " << j << " "
<< k << endl;
}
5. Write a C++ function repeat that takes a non-negative integer rep and a string s, and
returns a string that contains rep copies of s. This is a codestepbystep.com problem. Write a
main function that tests your repeat function.
6. Given the function below, what is the output of the call mystery(435)? This
is similar to a codestepbystep.com problem.
int mystery(int n) {
if(n < 10) return n;
else {
int a = n / 10;
int b = n % 10;
return mystery(a+b);
}
}
7. Write a recursive function evenDigits that takes an integer n and returns a new
integer containing only the even digits from n, in the same order. If n does not contain
any even digits, return 0.
evenDigits(43671)
returns 46
evenDigits(3517)
returns 0
8. Assume you have implemented binary search in a function binarySearch. Assume
the following:
int arr[] = {-4, -1, 2,
14, 23, 30, 45, 100, 166, 165, 435, 444, 286, 1000};
Which down the indices of the elements that are compared to the
search key when the following call is executed:
int find =
binarySearch(arr, 14, 2);
The second argument represents the size of the array.