Recursive Exercises

 

  1. Stars

    The program stars.cpp prints a line of stars both iteratively and recursively. Examine this file, then compile and run it.

    Make the following changes to stars.cpp.

    1. In the WriteStarsR function, change the cout statement to:
          cout << n << " ";

      Discuss what will happen, then compile and run.

    2. Move the WriteStars(n-1) line to right before the cout statement that is on the line before it. Discuss what will happen. Compile and run.
    3. Move the WriteStars(n-1) line to right before the if statement. Discuss what will happen. Compile and run.

     

  2. Mystery

    Examine the program mystery.cpp and discuss what it should do. Compile and run it.
     

  3. Matching Parentheses

    Write a program called parens.cpp that reads a file line by line and indicates whether the parentheses on each line match up (a right parenthesis for each left parenthesis which appears to the right of the left parenthesis). Note that a line can contain an arithmetic expression, symbols other than "(" and ")" are to be ignored, the focus is on whether or not the parentheses match correctly.

    Here is a sample run using the data file parens.in

    ()()()()()() matches!
    (((((()))))) matches!
    ()(((())))() matches!
    ( is missing a right parenthesis.
    ) is missing a left parenthesis.
    ((()(())) is missing a right parenthesis.
    (()(()))) is missing a left parenthesis.
    ())()( is missing a left parenthesis.
    (((((((((((((((()))))))))))))))) matches!

    You will need to complete the function checkParens. It must be a recursive function.
     

  4. Stutter

    Write a program called stutter.cpp that reads a list of words from a file and for each word prints the word with each letter appearing twice.

    Here is a sample run using the data file stutter.in

    hello = hheelllloo
    computer = ccoommppuutteerr
    Halloween = HHaalllloowweeeenn
    ghost = gghhoosstt

    You will need to complete the function stutter. It must be a recursive function.
     

  5. Adding Commas

    Write a program called commas.cpp that reads a file of numbers and prints each with commas in the right places.

    Here is a sample run using the data file commas.in

    1000 = 1,000
    1000000 = 1,000,000
    29 = 29
    999999 = 999,999
    2121212121 = 2,121,212,121

    You will need to complete the function printWithCommas. It must be a recursive function.