|
Homework 4
This homework is intended to gauge your understanding of functions and simple recursion in C++.
1) (10 points) Write the prototype and definition for a function that returns the median of 3 integers, call your function median.
2) (20 points) Write two overloaded functions that find the median of three floats and the median of three chars (your function names must all be median). Write a program to call these functions and the function from problem 1 and print the results.
3) (20 points) Write a templated function which finds the median of three ints, floats, or chars. Write a program to call this function and prints the results.
4) (25 points) Consider the following for loop. Now write a recursive function to replace the for loop.
Use the function prototype int resursive_add( int x, int y);
Your recursive function will add one to its argument x at each step and return the sum of all those additions. (Don't worry about negative numbers).
#include <iostream>
int main() { int x, y; cin >> x >> y;
for ( int i = 0; i < y; i++ ) { x++; }
cout << x << endl;
return 0; }
Your new main function should look like this after you are done:
#include <iostream>
int main() { int x, y;
cin >> x >> y;
x = recursive_add( x, y );
cout << x << endl;
return 0; }
5) (25 points) Consider the following for loops and their output. Now write a single recursive function which prints the same output as these for loops do together. Write a program to call your recursive function and print the results.
for ( int i = 0; i <= 10; i++ ) { cout << i << " "; }
for ( int i = 10; i >= 0; i-- ) { cout << i << " "; }
|