Loading...

Function recursively runs forever if value above 3 is input


As a mandatory preface, I am new to C, and am likely simply missing something extremely obvious. I appreciate any and all time and effort taken to look over my silly problem.

I have a recursive function whose purpose is to print out a large "x" made of smaller x characters, where width is the length of each side of the x. For example, a width of "3" would have the following output:

Shape:

X X
 X
X X

Returning.

Where "Returning." prints just before returning to main.

The following function does just this for a width of 1 and 3, but fails to do so with 5, 7, 9, etc.

void Recurse(int left, int right, int flag, int num){

int i;

    if(((left && right) == num/2) && (flag == 0)){
        for(i=0;i<num;i++){
            if (i == (num/2) ){
                printf("X");
            }
            else
                printf(" ");
        }
        printf("\n");
        flag = 1;
        Recurse(left-1, right+1, flag, num);
    }
    else if(flag == 0){
            for(i=0;i<num;i++){
                if((i == left) || (i == right)){
                printf("X");
            }
            else
                printf(" ");
        }
        printf("\n");
        Recurse(left+1, right-1, flag, num);
    }

    else if(flag == 1){
        for(i=0;i<num;i++){
            if((i == left) || (i == right)){
                printf("X");
            }
            else
                printf(" ");
        }
        printf("\n");
        if (((left == 0) && (right == num-1)) && (flag == 1))
                printf("\nReturning.\n");
            return;
        Recurse(left-1, right+1, flag, num);
    }
}

The only thing I have in my main function is an initialization of width with some odd int, and a call to the function. I would like to get the code actually... printing correctly prior to cleaning up the logic a bit. Thank you for any help provided.

- - Source

Answers

answered 1 week ago bruno #1

In

 if(((left && right) == num/2) && (flag == 0)){

left && right is a boolean value, probably you wanted

if ((left == num/2) && (right == num/2)  && (flag == 0)){

comments powered by Disqus