CS 215 ­ Fundamentals of Programming II  Fall 2013 ­ Homework 3

advertisement
CS 215 ­ Fundamentals of Programming II Fall 2013 ­ Homework 3
20 points
Out: September 11, 2013
Due: September 16, 2013 (Monday)
This is a written homework assignment. Turn in a hardcopy (either handwritten or printed out) of your answers.
1. (10 points) Consider the following program and answer the questions on the next page: // Function prototype
void sum_diff (int num1, int num2, int& num3, int& num4);
int main ()
{
int w, x, y, z;
x
y
z
w
}
=
=
=
=
4;
6;
3;
5;
cout << "
x
y
z
cout << "
<< "
" << x << "
" << z << "
" << y
" << w << endl;
sum_diff (x, y, z, w);
cout << "
" << x << "
<< "
" << z << "
" << y
" << w << endl;
sum_diff (z, w, y, x);
cout << "
" << x << "
<< "
" << z << "
return 0;
// end main
w" << endl;
" << y
" << w << endl;
// Function definition
void sum_diff (int num1, int num2, int& num3, int& num4)
{
num3 = num1 + num2;
num4 = num1 - num2;
} // end sum_diff
09/09/2013
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 num_digits that receives any integer and returns the number of digits that integer has. E.g., num_digits(2485) returns 4 while num_digits(-32) returns 2. 4. (5 points) Write a C++ function definition for an iterative (i.e., non­recursive) version of num_digits.
Note: you are not required to implement these functions in a program that runs, but you can if you want to.
09/09/2013
Page 2 of 2
D. Hwang
Download