A recursive function is a function that calls itself, reducing the problem a bit on each call:
void solveIt(the-Problem) {
. . .
solveIt(the-Problem-a-bit-reduced);
}
Recursive function example from Chapter 5 to print a triangle of “boxes”
[]
[][]
[][][]
[][][][]
void print_triangle(int side_length);
void print_triangle(int side_length) {
if (side_length < 1) { return; }
print_triangle(side_length - 1);
for (int i = 0; i < side_length; i++)
{
cout << "[]";
}
cout << endl;
}
Problem: What is the sum of 1’s in a triangular pattern? Or, what is the area of a triangle of height n?
Triangle number:
n = 1: 1 (1)
n = 2: 3 (2 + 1)
n = 3: 6 (3 + 2 + 1)
n = 4: 10 (4 + 3 + 2 + 1)
End condition: when side_length is 1, the triangle number (the area) is 1 and we are done.
int triangle_area(int side_length) {
if (side_length == 1) { return 1; }
. . .
}
int triangle_area(int side_length) {
if (side_length == 1) { return 1; }
int smaller_side_length = side_length - 1;
int smaller_area = triangle_area(smaller_side_length);
return smaller_area + side_length;
}
Add a test that handles the situation where side_length is less than or equal to 0.
int triangle_area(int side_length) {
if (side_length <= 0) { return 0; }
if (side_length == 1) { return 1; }
int smaller_side_length = side_length - 1;
int smaller_area = triangle_area(smaller_side_length);
return smaller_area + side_length;
}
/**
sec01/triangle.cpp
Computes the area of a triangle with a given side length.
@param side_length the side length of the triangle base
@return the area
*/
int triangle_area(int side_length) {
if (side_length <= 0) { return 0; }
if (side_length == 1) { return 1; }
int smaller_side_length = side_length - 1;
int smaller_area = triangle_area(smaller_side_length);
return smaller_area + side_length;
}
int main() {
cout << "Enter the side length: ";
int input;
cin >> input;
cout << "Area: " << triangle_area(input) << endl;
return 0;
}
Example:
void forever_young( ) {
cout << "I am " ;
forever_young();
cout << “forever young!" ;
}
This function prints out "forever young" forever.
Problem: Write a function to test if a string is a palindrome.
bool is_palindrome(string s)
Step 1: Break the input into parts that can themselves be inputs to the problem.
Focus on a particular input or set of inputs for the problem.
Think how you can simplify the inputs in such a way that the same function can be applied to the simpler input.
bool is_palindrome(string s) {
// Separate case for shortest strings
if (s.length() <= 1 ){ return true; }
...
// Get first and last character, converted to lowercase
char first = tolower(s[0]);
char last = tolower(s[s.length() - 1]);
if (first == last)
{
string shorter = s.substr(1, s.length() - 2);
return is_palindrome(shorter);
}
else
{
return false;
}
int main() {
cout << "Enter a string: ";
string input;
getline(cin, input);
cout << input << " is ";
if (!is_palindrome(input)) { cout << "not "; }
cout << "a palindrome." << endl;
return 0;
}
Enter a string: aibohphobia
aibohphobia is a palindrome.
/*
Tests whether a substring of a string is a palindrome.
@param s the string to test
@param start the index of the first character of the substring
@param end the index of the last character of the substring
@return true if the substring is a palindrome
*/
bool substring_is_palindrome(string s, int start, int end);
bool substring_is_palindrome(string s, int start, int end) {
// Separate case for substrings of length 0 and 1
if (start >= end) { return true; }
if (s[start] == s[end])
{
// Test substring that doesn’t contain
// the first and last letters
return substring_is_palindrome(s, start + 1, end - 1);
}
else
{
return false;
}
}
bool is_palindrome(string s) {
return substring_is_palindrome(s, 0, s.length() - 1);
}
char first_vowel(string str) {
if (str.length() == 0) { return '?'; } // No vowels
char first = str[0];
string rest = str.substr(1);
if (is_vowel(first)) { return first; }
else { return first_vowel(rest); }
}
char first_vowel(string str, int pos) { }
#include <iostream>
using namespace std;
/**
Computes a Fibonacci number.
@param n an integer (non-negative)
@return the nth Fibonacci number
*/
int fib(int n) {
if (n <= 2) { return 1; }
else return { fib(n - 1) + fib(n - 2); }
}
int main() {
cout << "Enter n: ";
int n;
cin >> n;
int f = fib(n);
cout << "fib(" << n << ") = " << f << endl;
return 0;
}
int fib(int n) {
cout << "Entering fib: n = " << n << endl;
int f;
if (n <= 2) { f = 1; }
else { f = fib(n - 1) + fib(n - 2); }
cout << "Exiting fib: n = " << n
<< " return value = " << f << endl;
return f;
}
int main() {
cout << "Enter n: ";
int n;
cin >> n;
int f = fib(n);
cout << "fib(" << n << ") = " << f << endl;
return 0;
}
Enter n: 6
Entering fib: n = 6
Entering fib: n = 5
Entering fib: n = 4
Entering fib: n = 3
Entering fib: n = 2
Exiting fib: n = 2 return value = 1
Entering fib: n = 1
Exiting fib: n = 1 return value = 1
Exiting fib: n = 3 return value = 2
Entering fib: n = 2
Exiting fib: n = 2 return value = 1
Exiting fib: n = 4 return value = 3
Entering fib: n = 3
Entering fib: n = 2
Exiting fib: n = 2 return value = 1
Entering fib: n = 1
Exiting fib: n = 1 return value = 1
Exiting fib: n = 3 return value = 2
Exiting fib: n = 5 return value = 5
Entering fib: n = 4
Entering fib: n = 3
Entering fib: n = 2
Exiting fib: n = 2 return value = 1
Entering fib: n = 1
Exiting fib: n = 1 return value = 1
Exiting fib: n = 3 return value = 2
Entering fib: n = 2
Exiting fib: n = 2 return value = 1
Exiting fib: n = 4 return value = 3
Exiting fib: n = 6 return value = 8
fib(6) = 8
#include <iostream>
using namespace std;
/**
Computes a Fibonacci number.
@param n an integer
@return the nth Fibonacci number
*/
int fib(int n) {
if (n <= 2) { return 1; }
int fold = 1;
int fold2 = 1;
int fnew;
for (int i = 3; i <= n; i++)
{
fnew = fold + fold2;
fold2 = fold;
fold = fnew;
}
return fnew;
}
bool is_palindrome(string s) {
int start = 0;
int end = s.length() - 1;
while (start < end)
{
if (s[start] != s[end]) { return false; }
start++;
end--;
}
return true;
}
vector<string> v = generate_permutations("eat");
for (int i = 0; i < v.size(); i++) {
cout << v[i] << endl;
}
// sec04/permute.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
Generates all permutations of the chars in a string.
@param word a string
@return a vector of all permutations of the word
*/
// sec04/permute.cpp
vector<string> generate_permutations(string word) {
vector<string> result;
if (word.length() == 0)
{
result.push_back(word);
return result;
}
for (int i = 0; i < word.length(); i++)
{
string shorter_word = word.substr(0, i)+ word.substr(i + 1);
vector<string> shorter_permutations =
generate_permutations(shorter_word);
for (int j = 0; j < shorter_permutations.size(); j++)
{
string longer_word = word[i] + shorter_permutations[j];
result.push_back(longer_word);
}
}
return result;
}
int main() {
cout << "Enter a string: ";
string input;
getline(cin, input);
vector<string> v = generate_permutations(input);
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
return 0;
}
generate_permutations("eat")
*
and /
bind more strongly than +
and -
term
+
term
factor
*
factor
expression
number
(
)
Term
Number
3
+
Factor
Number
4
*
Factor
Number
5
Factor
Expression
Term
Number
(
4
)
*
Factor
+ Number
5
3
expression_value
term_value
factor_value
expression_value
function first calls term_value
to get the value of the first term of the expression.term_value
again and adds or subtracts it:expression_value
Functionint expression_value(){
int result = term_value();
bool more = true;
while (more) {
char op = cin.peek(); //read char without removing
if (op == '+' | | op == '-') {
cin.get();
int value = term_value();
if (op == '+') {
result = result + value;
} else {
result = result - value;
}
}
else{
more = false;
}
}
return result;
}
term_value
Functionterm_value
function calls factor_value
in the same way, multiplying or dividing the factor values.int term_value(){
int result = factor_value();
bool more = true;
while (more){
char op = cin.peek();
if (op == '*' | | op == '/'){
cin.get();
int value = factor_value();
if (op == '*'){
result = result * value;
} else {
result = result / value;
}
}
else{
more = false;
}
}
return result;
}
factor_value
function checks whether the next input character is a '(' or a digit.factor_value
function makes a recursive call to expression_value
.factor_value
Functionint factor_value(){
int result = 0;
char c = cin.peek();
if (c == '(') {
cin.get();
result = expression_value(); //recursive call
cin.get(); // Read ")"
} else { // Assemble number value from digits
while (isdigit(c))
{
result = 10 * result + c - '0';
cin.get();
c = cin.peek();
}
}
return result;
}
main()
Program for Expressionsint main() {
cout << "Enter an expression: ";
cout << expression_value() << endl;
return 0;
}