Question 1: What is the output of the following program?
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int s(int n)
{
if (n == 0) return 0;
return n + s(n-1);
}
int main()
{
cout << s(10) << endl;
}
s(10) returns 10 + s(9).s(9) returns 9 + s(8).s(8) returns 8 + s(7).s(0) returns 0
s(n) returns $n + (n - 1) + .. + 2 + 1$, which is $n(n+1)/2$. The answer is $55$.
Question 2: What is the running time of s(n)?
(In these questions, use the carat symbol (^) for exponentiation).
Question 3: What is the output of the following program?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
string t(string v)
{
string tmp;
if (v.size() == 0) return "";
tmp.push_back(v[0]);
return t(v.substr(1)) + tmp;
}
int main()
{
cout << t("Fred") << endl;
}
s("Fred") sets tmp to "F" and calls s("red"). It returns s("red") + "F".s("red") sets tmp to "r" and calls s("ed"). It returns s("ed") + "r".s("ed") sets tmp to "e" and calls s("d"). It returns s("d") + "e".s("d") sets tmp to "d" and calls s(""). It returns s("") + "d".s("") returns "".s("d") returns "d".s("ed") returns "de".s("red") returns "der".s("Fred") returns "derF"."derF".
Question 4: What is the running time of t(v), where n = v.size()?
Question 5: What would be the running time of t(v) if v were a reference parameter?