-3

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.

273K
  • 29,503
  • 10
  • 41
  • 64
Leyla
  • 1
  • 3
  • 2
    Why does the function return a number? – molbdnilo Dec 22 '22 at 15:25
  • 1
    You need another recursive function that prints a row. – molbdnilo Dec 22 '22 at 15:26
  • That function only prints anything if `rows` is negative, but then it will never terminate. – molbdnilo Dec 22 '22 at 15:31
  • Change `if (rows >= 0)` to `if (rows == 0)`. – Tom Karzes Dec 22 '22 at 15:31
  • It returns zero without recursion for any initial value that is not negative. Walk through your own code and check for the obvious issues before posting a question. Either way you need two recursive functions, one for printing a row on n asterisks, and another from printing n rows of the triangle. – Clifford Dec 22 '22 at 16:38

2 Answers2

0

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);
    }
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

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;
}
Verbatim
  • 245
  • 1
  • 2
  • 8