CS 215 ­ Fundamentals of Programming II  Spring 2011 ­ Homework 4

advertisement
CS 215 ­ Fundamentals of Programming II Spring 2011 ­ Homework 4
20 points
Out: January 26
Due: January 31 (Monday)
This is a written homework assignment. Turn in a hardcopy (either handwritten or printed out).
1. (10 points) Consider the following program and answer the questions on the next page: // Function prototype
void SumDiff (int num1, int num2, int& num3, int& num4);
int main ()
{
int w, x, y, z;
x = 4; y = 6; z = 3; w = 5;
cout << " x y z w" << endl;
cout << " " << x << " " << y << " " << z << " " << w << endl;
SumDiff (x, y, z, w);
cout << " " << x << " " << y << " " << z << " " << w << endl;
SumDiff (z, w, y, x);
cout << " " << x << " " << y << " " << z << " " << w << endl;
return 0;
} // end main
// Function definition
void SumDiff (int num1, int num2, int& num3, int& num4)
{
num3 = num1 + num2;
num4 = num1 ­ num2;
} // end SumDiff
01/24/2011
Page 1 of 2
D. Hwang
a)
b)
c)
d)
e)
f)
Which variables are value parameters? Which variables are reference parameters? What is the difference between a value parameter and a reference parameter? Which variables are arguments?
What is the difference between a parameter and an argument?
What is the output of this program? Note there are 4 lines of output.
2. (5 points) Consider the following recursive function and answer the questions that follow.
int Choose (int n, int k)
{
if (k == 1)
return n;
else if (n == k)
return 1;
else
return Choose (n­1, k­1) + Choose (n­1, k);
}
a) What is/are the base case(s) of this function?
b) What is/are the recursive step(s) of this function?
c) What is the result of the function call Choose(5,2)?
3. (5 points) Write the C++ function definition for a recursive function NumDigits that receives a positive integer and returns the number of digits that integer has. E.g., NumDigits(2485) returns 4 while NumDigits(32) returns 2. 4. (5 points) Write a C++ function definition for an iterative (i.e., non­recursive) version of NumDigits.
Note: you are not required to implement these functions in a program that runs, but you can if you want to.
01/24/2011
Page 2 of 2
D. Hwang
Download