Home > Mobile >  printing triangle using recursion in c without loop or multiplication
printing triangle using recursion in c without loop or multiplication

Time:12-23

I'm supposed to print a triangle int tri(int rows) in c using recursion without multiplication or loops. The triangle should have one * in the 1st row, two ** in the 2nd row, three *** in the 3rd row and so on...

here's what I tried and what seems to work in other peoples code, but not in mine. I sadly cannot see the error yet:

#include <stdio.h>


int triangle(int rows){


    if(rows >= 0){

           return 0;

       }
        else if(rows == 1){
        printf("*");
        return 1;
       }

       else{
       printf("*");
       return rows   triangle(rows-1) ;



}
}

int main()
{
    triangle(5);
    return 0;
}

I'm guessing it has something to do with the printing part, I thought about making an own variable for that but since I'm not allowed to use multiplication, I don't know how I could describe it. I want to know what my logical problem is right here and how I could solve it easily.

CodePudding user response:

Imagine that you had a function void line(n) that prints n asterisks on one line.
Then you could write

void triangle(int n)
{
    // Print the smaller triangle first, if there should be one.
    if (n > 0)
    {
        triangle(n-1);
    }
    // Then add the last line after the smaller triangle.
    line(n);
}

All that remains is to add the lines:

void line(int n)
{
    if (n <= 0)
    {
        // End of line.
        printf("\n");
    }
    else
    {
        // Print an asterisk, and then the rest of the line.
        printf("*");
        line(n-1);
    }
}

CodePudding user response:

Here's a slightly different version which uses just one set of recursive calls.

The second recursive call is replaced by using the printf statement to simply output the desired number of stars on each line.

/* triangle.c */

#include <stdio.h>

void triangle(int num)
{
    if (num > 1) {
        triangle(num - 1);
    }

    printf("%.*s\n", num, "****************");
}

int main (void)
{
    triangle(16);

    return 0;
}
  • Related