Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right triangle using recursion in C

Tags:

c

char

recursion

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?

like image 843
Matthew Avatar asked Mar 01 '26 06:03

Matthew


1 Answers

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); 
}
like image 132
senoron Avatar answered Mar 02 '26 21:03

senoron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!