APS105 Textbook 11.2 - Recursion in Patterns
Print a Triangle of Stars Using Recursion
Say you want to print the following pattern based on the number of lines inputted:
Number of lines: 5
*****
****
***
**
*
You can do this using recursion (again, you could just do this iteratively, but whatever).
Code
#include <stdio.h>
void printRow(int n) {
// doing this part iteratively because I refuse to do it recursively
for (int i = 0; i < n; ++i) {
printf("*");
}
printf("\n");
}
void printTriangle(int row) {
if (row == 1) {
// base step
printf("*\n");
} else {
// recursive step
printRow(row);
printTriangle(row - 1);
}
}
int main(void) {
int lines = 5;
printf("Number of lines: %d\n", lines);
printTriangle(lines);
return 0;
}
Print an Inverted Triangle of Stars Using Recursion
Say you want to print the following pattern based on the number of lines inputted:
Number of lines: 5
*
**
***
****
*****
You can do this using recursion (again, you could just do this iteratively, but whatever).
Code
#include <stdio.h>
void printRow(int row, int lines) {
// doing this part iteratively because I refuse to do it recursively
for (int col = row - 1; col < lines; ++col) {
printf("*");
}
printf("\n");
}
void printTriangle(int row, int lines) {
if (row == 1) {
// base step
printRow(row, lines);
} else {
// recursive step
printRow(row, lines);
printTriangle(row - 1, lines);
}
}
int main(void) {
int lines = 5;
printf("Number of lines: %d\n", lines);
printTriangle(lines, lines);
return 0;
}
Print a Pattern Recursively
Say you want to print the following pattern based on the number of lines inputted:
Enter number of max stars in a row: 5
*****
****
***
**
*
*
**
***
****
*****
Code
#include <stdio.h>
void printRow(int n);
void printPattern(int n);
int main(void) {
int rows;
printf("Enter number of max stars in a row:\n");
scanf("%d", &rows);
int rowsOverwrite = 5;
printPattern(rowsOverwrite);
return 0;
}
void printPattern(int n) {
if (n > 0) {
printRow(n);
printPattern(n - 1); // recursive step
printRow(n);
}
}
void printRow(int n) {
if (n == 1) {
// base step
printf("*\n");
} else {
// recursive step
printf("*");
printRow(n - 1);
}
}
The reason this works is because printPattern(n-1) always runs before the second printRow, but after the first printRow. Thus, the recursive step is always squished between the printRow calls, which mirrors the output.
Also note that there is straight up no base step in the printPattern function; instead, the function just stops running.
This is because the function could just stop running after it reaches the base step condition