Ch. 14 Exercises (CSCI 121)

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Trace the recursive solution for the function below (prints 1,2, ..., n), if n = 3: void writeUp(int n) { if (n >= 1) { writeUp(n - 1); cout << n << " "; } }

// the code to be executed is if (3 >= 1) { writeUp(3 - 1); cout << 3 << " "; } // on the next recursion, n = 2 if (2 >= 1) { writeUp(2 - 1); cout << 2 << " "; } // on the next recursion, n = 1 if (1 >= 1) { writeUp(1 - 1); cout << 1 << " "; } // on the final recursion, n = 0 if (0 >= 1) // condition false, body skipped { // skipped } // the recursions unwind; the output is 1, 2, 3

What is the output of the following program? #include <iostream> using namespace std; int mystery(int n); // pre-condition: n >= 1 int main() { cout << mystery(3); return 0; } int mystery(int n) { if (n <= 1) return 1; else return (mystery(n - 1) + n); }

6

#include <iostream> using namespace std; void cheers(int n); int main() { cheers(3); return 0; } void cheers(int n) { if (n == 1) { cout << "Hurray \n"; } else { cout << "Hip "; cheers(n - 1); } }

Hip Hip Hurray

What is the output of the following program? What well-known mathematical function is rose? #include <iostream> using namespace std; int rose(int n); // pre-condition: n >= 0 int main() { cout << rose(4); return 0; } int rose(int n) { if (n <= 0) return 1; else return (rose(n - 1) * n); }

The output is 24. The function is the factorial function, usually written n! and defined as follows: n! is equal to n * (n - 1) * (n - 2) * ... * 1

Two non-negative integers x and y are equal if either: Both are 0, or x-1 and y-1 are equal Write a bool-function named equals that recursively determines whether its two int parameters are equal and returns true if they are and false otherwise.

bool equals (int x, int y) { if( (x<0) || (y<0) ) return false; if( (x==0) && (y==0) ) return true; return equals(x-1, y-1); }

Write a recursive, int-valued function, len, that accepts a string and returns the number of characters in the string. The length of a string is: 0 if the string is the empty string (""). 1 more than the length of the rest of the string beyond the first character.

int len(string s) { if(s=="") return 0; else { return 1+len(s.erase(0,1)); } }

Write an iterative version of the function below (prints n number of asterisks in a single row): void asterisk(int n) { if (n <= 1) { cout << "*"; } else { asterisk(n - 1); cout << "*"; } }

void asterisk(int n) { for (int count = 1; count <= n; count++) cout << '*'; }

Write a recursive void function that has one parameter which is a positive integer and that writes out that number of asterisks '*' to the screen all on one line.

void asterisk(int n) { if (n <= 1) { cout << "*"; } else { asterisk(n - 1); cout << "*"; } }

Write a recursive void function that has one parameter, which is a positive integer. When called, the function writes its argument to the screen backward. That is, if the argument is 1234, it outputs the following to the screen: 4321

void backward(int n) { if (n < 10) { cout << n; } else { cout << (n % 10); //write the last digit backward(n / 10); // write the other digits backward } }

Write an iterative version of the function below (print n backwards): void backward(int n) { if (n < 10) { cout << n; } else { cout << (n % 10); //write the last digit backward(n / 10); // write the other digits backward } }

void backward(int n) { while (n >= 10) { cout << (n % 10); //write last digit n = n / 10; //discard the last digit } cout << n; }

Write an iterative version of the function definition below: void cheers(int n) { if (n == 1) { cout << "Hurray \n"; } else { cout << "Hip "; cheers(n - 1); } }

void cheers(int n) { while (n > 1) { cout << "Hip "; n--; } cout << "Hurray\n"; }

The nth harmonic number is defined non-recursively as: 1 +1/2 + 1/3 + 1/4 + ... + 1/n. Come up with a recursive definition and use it to guide you to write a function definition for a double-valued function named harmonic that accepts an int parameters n and recursively calculates and returns the nth harmonic number.

double harmonic(int n) { if(n==0) return 0.0; else return 1.0/ n + harmonic(n-1); }

Assume the availability of a function named printStars that can be passed a non-negative integer n and print a line of asterisks. Write a function named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows: first a line of 1 asterisk, followed by a line of 2 asterisks, and then a line of 3 asterisks, and so on and finally a line of n asterisks. For example, if the function received 5 it would print:** ** * ** * * ** * * * * The function must not use a loop of any kind (for, while, do-while) to accomplish its job. The function should invoke printStars to accomplish the task of printing a single line.

void printTriangle (int n) { if(n==0) return; printTriangle(n-1); printStars(n); cout << endl; }

Assume the availability of a function named printStars that can be passed a non-negative integer n and print a line of asterisks. Write a function named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows: first a line of n asterisks, followed by a line of n-1 asterisks, and then a line of n-2 asterisks, and so on. For example, if the function received 5 it would print: ***** **** *** ** * The function must not use a loop of any kind (for, while, do-while) to accomplish its job. The function should invoke printStars to accomplish the task of printing a single line.

void printTriangle(int n){ if(n <= 0) return; printStars(n); cout<<endl; printTriangle(n-1); }

Write the definition of a function named rcopy that reads all the strings remaining to be read in standard input and displays them, one on a line with no other spacing, onto standard output IN REVERSE ORDER. So if the input was:here comes the sun the output would be sun the comes here The function must not use a loop of any kind (for, while, do-while) to accomplish its job.

void rcopy() { string s; cin>>s; if(cin.fail()) return; rcopy(); cout<<s<<endl; }

A palindrome is a string that reads the same forwards or backwards; for example dad, mom, deed (i.e., reversing a palindrome produces the same string). Write a recursive, bool-valued function, isPalindrome that accepts a string and returns whether the string is a palindrome. A string, s, is a palindrome if: s is the empty string or s consists of a single letter (which reads the same back or forward), or the first and last characters of s are the same, and the rest of the string (i.e., the second through next-to-last characters) form a palindrome.

bool isPalindrome(string s) { if (s.length() < 2) return true; else if (s[0] == s[s.length() - 1]) return isPalindrome(s.substr(1,s.length()-2)); return false; }

Assume the availability of a function called printStars. The function receives an int argument. If the argument is positive, the function prints (to standard output) the given number of asterisks. Thus, if printStars(8) is called, ******** (8 asterisks) will be printed. Assume further that the variable starCount has been declared and initialized to a some integer, possibly negative or zero. Write some code that does nothing if starCount is not positive but that otherwise prints starCount asterisks to standard output by: first printing a single asterisk (and no other characters) then calls printStars to print the remaining asterisks.

if (starCount > 0){ cout << "*"; printStars(starCount-1); }

If your program produces an error message that says stack overflow, what is a likely source of the error?

infinite recursion

Write the definition of a function named count that reads all the strings remaining to be read in standard input and returns their count (that is, how many there are) So if the input was:hooligan sausage economyruin palatialthe function would return 5 because there are 5 strings there. The function must not use a loop of any kind (for, while, do-while) to accomplish its job.

int count() { string q = ""; cin >> q; int word_count = 0; if(q != "") word_count += 1 + count(); else word_count = 0; return word_count; }

The maximum-valued element of an integer-valued array can be recursively calculated as follows: If the array has a single element, that is its maximum (note that a zero-sized array has no maximum) Otherwise, compare the first element with the maximum of the rest of the array-- whichever is larger is the maximum value. Write an int function named max that accepts an integer array, and the number of elements in the array and returns the largest value in the array. Assume the array has at least one element.

int max(const int arr[], int n) { if (n == 1) return arr[0]; else { if (max(arr, n-1) > arr[n-1]) return max(arr, n-1); else return arr[n-1]; } }

Write the definition of a function called product. The function receives two int parameters. You may assume that neither parameter is negative. The function returns the product of the parameters. So, product(3,5) returns 15 and product(30,4) returns 120. The function must not use a loop of any kind (for, while, do-while) to accomplish its job.

int product(int x, int y) { return (x*y); }

Write a recursive, int-valued function named productOfOdds that accepts an integer array, and the number of elements in the array and returns the product of the odd-valued elements of the array. You may assume the array has at least one odd-valued element. The product of the odd-valued elements of an integer-valued array recursively may be calculated as follows: If the array has a single element and it is odd, return the value of that element; otherwise return 1. Otherwise, if the first element of the array is odd, return the product of that element and the result of finding the product of the odd elements of the rest of the array; if the first element is NOT odd, simply return the result of finding the product of the odd elements of the rest of the array

int productOfOdds(int array[],int length) { int product=1; if(length==0) return -1; else if(length==1) { if(array[length-1]%2!=0) return array[length-1]; else return 1; } else { product=productOfOdds(array,--length); if(array[length]%2!=0) { product=product*array[length]; } } return product; }

The sum of the elements of an integer-valued array recursively calculated as follows: The sum of an array of size 0 is 0; Otherwise, the sum is the value of the first element added to the sum of the rest of the array. Write an int-valued function named sum that accepts an integer array, and the number of elements in the array and returns the sum of the elements of the array.

int sum(int array[],int size) { int sumVal; if(size==0) return 0; else { sumVal=sum(array,--size); sumVal=sumVal+array[size]; } return sumVal; }

Given non-negative integers x and n, x taken to the nth power can be defined as: x to the 0th power is 1 x to the nth power can be obtained by multiplying x to the n-1'th power with x Write a long-valued function named power that accepts two int parameters x and n (in that order) and recursively calculates and returns the value of x taken to the n'th power.

long power(int x, int n) { if(n==0) return 1; else{ return x* power(x, n-1); } }

Write a recursive, string-valued function, replace, that accepts a string and returns a new string consisting of the original string with each blank replaced with an asterisk (*) Replacing the blanks in a string involves: Nothing if the string is empty Otherwise:If the first character is not a blank, simply concatenate it with the result of replacing the rest of the stringIf the first character IS a blank, concatenate an * with the result of replacing the rest of the string

string replace(string sentence){ if(sentence.empty()) return sentence; string newString; if(sentence[0] == ' ') { newString.append("*" + replace(sentence.substr(1))); } else { newString.append(sentence[0] + replace(sentence.substr(1))); } return newString; }

Write the definition of a function named printPowerOfTwoStars that receives a non-negative integer N and prints a line consisting of "2 to the N" asterisks. So, if the function received 4 it would print 2 to the 4 asterisks, that is, 16 asterisks: **************** and if it received 0 it would print 2 to the 0 (i.e. 1) asterisks: * The function must not use a loop of any kind (for, while, do-while) to accomplish its job.

void printPowerOfTwoStars( int n ) { if( n == 0 ) std::cout << '*' ; else if( n > 0 ) { printPowerOfTwoStars( n-1 ) ; printPowerOfTwoStars( n-1 ) ; } }

Write a recursive void function that takes a single int argument n and writes integers n, n-1, ..., 3, 2, 1

void writeDown(int n) { if (n >= 1) { cout << n << " "; writeDown(n - 1); } }

Write a recursive void function that takes a single int argument n and writes the integers 1, 2, ..., n

void writeUp(int n) { if (n >= 1) { writeUp(n - 1); cout << n << " "; } }

Assume the availability of a function called fact. The function receives an int argument and returns an int value. If the argument is one or smaller, it returns the integer value one. Otherwise it returns the product of all the integers from one to its argument.So the value of fact(4) is 1*2*3*4 and the value of fact(10) is 1*2*3*4*5*6*7*8*9*10.Assume further that the variable k has been declared and initialized to a positive integer.Assume further that the variable x has been declared as an integer type.Write a statement that assigns x the value k*(k-1)*(k-2)*...*3*2*1 by calling the fact function and multiplying its return value by k.Note: your solution must include multiplying fact's return value by k here.

x=fact(k-1)*k;


Ensembles d'études connexes

Chapter 8 American National Government Final Exam Review

View Set

مراجعة قوانين مساحات الأشكال الهندسية

View Set

Module 3 Earthquakes and Earth's Interior

View Set

SUPA Economics Chapter 4 Objectives

View Set

Chapter 10: Making Decisions and Solving Problems

View Set

6.4 India Becomes a British Colony

View Set

Chapter 9 - Lesson 3 - U.S. Supreme Court

View Set