// User-defined enum type for represent different shapes
enum Shape {TRIANGLE, HIVE, VERTICAL, HORIZONTAL, UPWARD_SLANTING_LINE, DOWNWARD_SLANTING_LINE, NONE};
/* Function Given */
// This function is used for printing out the Canvas
void printCanvas(char canvas[MAX_ROW][MAX_COL]);
/* TODO: Functions to be completed in pa2.cpp */
// Recursive functions for making lines
int makeHorizontalLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length);
int makeVerticalLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length);
int makeUpwardSlantingLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length);
int makeDownwardSlantingLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length);
Question
How can I write the 4 drawing function by using recursion, Please give me some hints or example, I don't have any idea of it. Thanks
makeHorizontalLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length);
int makeVerticalLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length);
int makeUpwardSlantingLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length);
int makeDownwardSlantingLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length);
First, I think you need to reconsider you printCanvas() function. I’m pretty sure a simple nested-loop to print the rows of the canvas to cout is all it needs.
Recursion is another way of writing a loop.
For example, to draw a horizontal line, you would normally just write a loop:
1 2 3 4 5 6 7
typedefchar Canvas[MAX_ROW][MAX_COL];
void makeHorizontalLine( Canvas canvas, int row, int col, int length )
{
for (int n = 0; n < length; n++)
canvas[row][col + n] = '-';
}
The trick is to turn that loop into a recursive function.
The only thing that changes in the loop is n. We use it to remember how many items we have printed, up to length items.
Another way of thinking about it is: how many items are there left to print?
Rewriting:
1 2 3 4 5
void makeHorizontalLine( Canvas canvas, int row, int col, int length )
{
while (length--)
canvas[row][col++] = '-';
}
The only things that change each loop are length-- and col++, and we never need to use the old values again. This suggests a recursive version. A line is split into the first cell, plus all remaining cells.
1 2 3 4 5 6 7 8
void makeHorizontalLine( Canvas canvas, int row, int col, int length )
{
if (!length) return; // length == 0? We're done.
canvas[row][col] = '-'; // the first cell of the line
makeHorizontalLine( canvas, row, col+1, length-1 ); // all remaining cells (if any)
}
Do you see how the loop and the recursion are the same thing?