I need help with a program. I have to write a recursive function to print a right triangle such as this (for n == 4):
*
* *
* * *
* * * *
n is the length of foundation. I may not use loops, global variables, or the static keyword.
So far I have a program printing n:
#include <stdlib.h>
void triangle(int n);
int main() {
int n;
printf("Write n: ");
scanf("%d", &n);
triangle(n);
return 0;
}
void triangle(int n) {
if (n != 0) {
triangle(n - 1);
printf("%d", n);
printf("\n");
}
}
So how can I print a triangle like this, and will be my program helpful for doing this task?
If you want to use recursion your code should be like this:
#include <stdio.h>
// function to print a row
void printn(int num);
// function to print the pattern
void pattern(int n, int i);
// driver function
int main()
{
int n;
if(scanf("%d", &n) != 1)
{
printf("Invalid number");
return 1;
}
pattern(n, 1);
return 0;
}
void pattern(int n, int i)
{
// base case
if (n == 0)
return;
printn(i);
printf("\n");
// recursively calling pattern()
pattern(n - 1, i + 1);
}
void printn(int num)
{
// base case
if (num == 0)
return;
printf("* ");
// recursively calling printn()
printn(num - 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With