void r(int x, int y, int& z) { cout << "r: x = " << x << " y = " << y << " z = " << z << endl; x = x + 1; z = y + x; } void t() { int a, b, x; a = 20; b = 25; x = 250; r(a,b,x); r(x,a,b); cout << "t: a = " << a << " b = " << b << " x = " << x << endl; }
Answer:
The key to getting this right is to do the hand simulation
carefully. Be sure to remember how to handle call-by-reference
and call-by-value. Before the first call to r, the picture looks
like this.
Now r(a,b,x) is called. The picture looks like this.
r: x = 20 y = 25 z = 250
r: x = 46 y = 20 z = 25
t: a = 20 b = 67 x = 46
t
----------
a = 20
b = 25
x = 250
t r
---------- ---------
a = 20 x = 20
b = 25 y = 25
x = 250 <- z .
|___________|
When function r runs, it prints line
r: x = 20 y = 25 z = 250
and then performs the two assignments. The picture looks like this.
t r
---------- ---------
a = 20 x = 21
b = 25 y = 25
x = 46 <- z .
|___________|
Now r returns, and t is about to call r again. The picture is like this.
t
----------
a = 20
b = 25
x = 46
Now t calls r(x,a,b). The picture looks like this just before r
runs.
t r
---------- ---------
a = 20 x = 46
b = 25 <- y = 20
x = 46 | z .
|___________|
Now r runs. It prints line
r: x = 46 y = 20 z = 25
Then r does the two assignments. The picture is like this.
t r
---------- ---------
a = 20 x = 47
b = 67 <- y = 20
x = 46 | z .
|___________|
Now r returns, leaving t ready to print its line. It prints
t: a = 20 b = 67 x = 46
int mystery(int n) { if(1 == n) return 1; else return 3*mystery(n-1); }
You can find out the value of mystery(4) by computing mystery(1), mystery(2) and mystery(3) first.
mystery(1) = 1 mystery(2) = 3*mystery(1) = 3*1 = 3 mystery(3) = 3*mystery(2) = 3*3 = 9 mystery(4) = 3*mystery(3) = 3*9 = 27The key to getting this kind of question right is to stay organized, and not to be sloppy.
Answer: 27
int whatisthis(int n) { if(n == 0) return 1; else return whatisthis(n-1) + whatisthis(n-1); }
This is similar to the preceding question. Find out what the small values lead to first. Don't be sloppy.
whatisthis(0) = 1 whatisthis(1) = whatisthis(0) + whatisthis(0) = 1 + 1 = 2 whatisthis(2) = whatisthis(1) + whatisthis(1) = 2 + 2 = 4 whatisthis(3) = whatisthis(2) + whatisthis(2) = 4 + 4 = 8
Answer: 8
ifstream in("mydata.txt");
in >> n;
ofstream out("myout");
out << n;
Remark. There was a mistake in this
question. It should have been as stated above.
struct Plant { int root; double leaf; };Write C++ statements that will create an object called bush of type Plant, and will set bush so that its root variable holds 12 and its leaf variable holds 90.0.
Plant bush; bush.root = 12; bush.leaf = 90.0;