Home > Software design >  Building a half tree in C
Building a half tree in C

Time:12-08

I am trying to build the following half-tree form

x
xx
xxx
xxxx
xxxxx
....
N xxxxx

but I cannot get to the "*" in the middle. Instead I have the gaps generated by the second loop.

The code I used:

#include <stdio.h> 

main(){ 
    int N;
    int i,j;
    printf("Enter the number: "); 
    scanf("%d",&N);
    for (i=1;i<=N;i  ){
        printf("x"); 
        for(j=1; j<=(N-i); j  ){ 
        printf(" "); 
        }
        printf("x");
        printf("\n");
    }
}

Could you please advise how am I going to populate the *s?

Thank you in advance.

edit based on the comments

If I change the printf(" "); with printf("x"); I get an inverted half tree, like the one below for N=6

xxxxxx
xxxxx
xxxx
xxx
xx
x

CodePudding user response:

Change the condition in your second for loop from j<=(N-i) to j < i. See below.

halfTree.c

#include <stdio.h>

int main(int argc, char * argv[]){
    int N;
    int i, j;

    N = atoi(argv[1]);

    for(i=0; i < N; i  )
    {
        printf("*");

        for(j=0; j < i; j  )
            printf("*");

        printf("\n");
    }

    return 0;
}

Compile and run the above using the commands below

gcc halfTree.c -o halfTree
./halfTree 4
  • Related