Shams Mohammed
Shams Mohammed

Reputation: 5

Triangle with Recursion

I have an assignment from my uni where I have to print a triangle using recursion in C language. I have tried writing my code as follows but I am not able to find my mistake. Kindly can anyone point out where I have to edit.

int tri(int x, int org);
int dreick(int x) {
    return tri(x,x);
}
int tri(int x,int org) {
    if (x == 0) {
        return 0;
    }
    else {
        return (x - 1, org);
    }
    for (int i = 0; i < (org - x); i++) {
        printf("");
    }
    for (int j = 0; j <= x; j++) {
        printf("*");
    }printf("\n");

}



int main() {
    int a = dreick(5);
    printf("%d",a);
}

Upvotes: 0

Views: 128

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 61993

Recursion works as follows: each step receives a parameter which specifies what work still needs to be done; if no work needs to be done, then it returns without doing anything; otherwise, it does one step of the work, and then invokes itself with a new value for the parameter which specifies the remaining work to be done.

In your case, the parameter specifying what work still needs to be done can be the row number.

Your triangle-printing code can print the top (single star at row 0) and the bottom (row of stars at row N) outside of recursion, so as to keep things simple. Use recursion to print each line of text from 1 to N-1.

On each step of the recursion you print a number of spaces, an asterisk, some more spaces, and then another asterisk. The number of spaces depends on the row number. (How deep down the triangle you are.) You are done when you reach N-1.

Upvotes: 2

Related Questions