Lab 11: Recursion
Quiz:
The quiz will be available during the first 5 minutes of lab:
Your lab TA will tell you the password you will need to get into the quiz for your section.
You may use either one of the lab machines or your own laptop.
For the lab computers your account name and password are the same as your UIC NetID and password.
Please Click on Your Lab Time: 9am, 10am, 11am, 12pm, 1pm, 2pm, 3pm, 4pm, 5pm
Lab ZyBooks 10.10:
Recursion in simple terms is "Re - occur". So far you have written loops and executed iterative programs.
In this lab you will take functions that work non-recursively (iteratively), and you will rewrite them to work recursively.
The three functions you will need to implement are:
Stage 1: Display Odd Numbers(1 Point)
For reference you have been given the iterative function problemOneOddNumbersIterative. This function takes a number as input and displays all the odd numbers smaller than this number. You are to write the function that does exactly the same thing, but does it using recursion.
Shown below is the iterative version
void problemOneOddNumbersIterative( int counter, int limit)
{
// Display numbers up to the limit
while( counter < limit) {
if( counter % 2 == 1) {
cout << counter << " ";
}
counter++;
}
cout << endl; // display a new line
}//end problemOneOddNumbersIterative()
Stage 2: Count Upper case alphabets (1 Point)
For reference you have been given the iterative function problemTwoCountUpperRecursive. This function takes a string as input and counts the number of upper case alphabets in it. You are to write the function that does exactly the same thing, but does it using recursion.
Shown below is the iterative version
int problemTwoCountUpperIterative( int index, string letters)
{
int counter = 0;
while( index < letters.length() ) {
char currentChar = letters[ index]; // first character
// If the current character is upper case, increment counter
if( isupper( currentChar)) {
counter++;
}
// advance pointer to next character
index++;
}
return counter;
}//end problemTwoCountUpperIterative()
Stage 3: Finish the Fibonacci Sequence Given (EC: 1 Point)
Uncomment the body of the problem 3 and fill in the missing portions. Fibnum1 and Fibnum2 have starting values of 0 and 1 respectively.
void problemThreeFibonacci(int fibNum1, int fibNum2, int limit)
{
// Possible cout location
if ((????) > limit) { // Base case
// Possible cout location
return;
}
else { // Recursive case
// Possible cout location
// What/How do we update fibnum2?
// Does the limit change when we recursively call the function?
problemThreeFibonacci(fibNum2, ??????, ?????);
}
// Possible cout location
}//end problemThreeFibonacci()