Search code examples
cnested-loops

How to put variable on nested loop?


I want to put make a box of variable. I don't know where I make a mistake?

int i;

for(i=0;i<=w;i++) {
    printf("%c ",c);
    int j;
    for(j=0;j<=h;j++){
        printf("%c ",c);
    }
    printf("\n");
}

I want my output like this :

L L L L L
L L L L L
L L L L L

Solution

  • Here's a modified version of your code (the comments in the code point out the changes I've made):

    int i;
    for(i=0;i<h;i++){ //changed <= to < (since i is starting from 0) or it would've printed an extra row of L's
        //also, it should be i<h not i<w (considering h is the height of the rectangle)
        //removed printf("%c ",c); from here as well to avoid printing an extra L at the beginning of each row
        int j;
        for(j=0;j<w;j++){ //changed <= to < in this case too or it would've printed an extra L at the end of each row
        //changed j<h to j<w as well (considering w is the width of the rectangle)
            printf("%c ",c);
        }
        printf("\n");
    }