I am a newbie to C. I tried to implement a serial drawPyramid
function. Now, I want to implement a recursive version of this function drawPyramid_rec
for my own practice. However, I am stuck for hours. No ideas how to deal with the leading whitespaces in each row... I felt like somehow I have to store the value of n
in the first recursive call. Or perhaps there is no possibility to implement a recursive version of drawPyramid
? Please help!
#include <stdio.h>
void drawPyramid(int n);
int main(void)
{
int n;
do
{
printf("Height: ");
scanf("%i", &n);
}
while (n > 8 || n < 1);
drawPyramid(n);
return 0;
}
void drawPyramid(int n)
{
for (int height = 1; height <= n; ++height)
{
for (int column = (n - height); column >= 1; --column)
{
printf(" "); // putchar(' ');
}
for (int column = 1; column <= height; ++column)
{
putchar('#'); // printf("#");
}
printf(" ");
for (int column = 1; column <= height; ++column)
{
printf("#");
}
printf("\n");
}
}
Output:
Height: 5
# #
## ##
### ###
#### ####
##### #####
I felt like somehow I have to store the value of
n
in the first recursive call.
Yes, you have to preserve the value of n
, which is the height of the pyramid. To do that, you could add an extra parameter to your function drawPyramid
that never changes it.
void drawPyramid_recursive(int n, int height)
{
if (height == 0) // base case
{
return;
}
drawPyramid_recursive(n, height - 1);
for (int column = (n - height); column >= 1; --column)
{
printf(" "); // putchar(' ');
}
for (int column = 1; column <= height; ++column)
{
putchar('#'); // printf("#");
}
printf(" ");
for (int column = 1; column <= height; ++column)
{
printf("#");
}
printf("\n");
}