Homework 21 Solution

Write a recursive function


void rectangle(int rowNum, int colNum, ostream &OUT);

that prints out rectangles of *'s with rowNum rows and colNum columns. In the spirit of bottom-up design, I'll provide you with a function you may want to use:

void rep(char c, int k, ostream& OUT)
  for(int i = 0; i < k; i++)
    OUT << c;

Test your function with a program that reads the dimensions of the rectangle (you may assume non-negative integer input from the user) and the destination (screen or file) that you’re writing to from the user, something like this:

How many rows? 8
How many columns? 3
(S)creen or (F)ile? S

Turn In a printout of your program, hw21.txt, and two screen captures, one showing your program run on the above example with output going to the screen, and another showing the same input with the output going to a file called hw21.txt.



// KGS
// recursive rectangle

#include <fstream>
#include <string>
using namespace

void rectangle(int, int, ostream&);
void rep(char, int, ostream&);

int main (){
    int rows,cols;
    char where;

    cout << "This program was written by KGS." << endl;
    cout << "It prints a rectangle of *'s." << endl;
    cout << "How many rows? ";
    cin >> rows;
    cout << "How many columns? ";
    cin >> cols;
    cout << "(S)creen or (F)ile? ";
    cin >> where;

    if (where == 'F'){
        string name;
        cout << "Enter the name of the output file: ";
        cin >> name;
        ofstream fout(name.c_str());

    return 0;

void rectangle(int r, int c, ostream & out){
    if (r==0)  // base case, nothing to print
    else{      // recursive case
        rep('*',c,out);  // print a c number of * on a row
        out << endl;     // newline
        rectangle(r-1,c,out);  // recursive call for 1 less row

void rep(char c, int k, ostream& out){
    for(int i = 0; i < k; i++)
    out << c;