Home > front end >  Use nested C loops to produce the following out put
Use nested C loops to produce the following out put

Time:10-05

Am a beginner in C and I came across this question, How to produce the following pattern using C nested loops

BBBBBBB
BBBBBB
BBBBB
BBBB
BBB
BB

Code

# include <stdio.h>
int main()
{
    int Row, Col;
    for(Row = 7; Row >= -13; Row--)
    {
        for(Col = 1; Col <= Row; Col  )
       {
            printf("B");
        
        }
        printf("\n");
    }
    return 0;
}

CodePudding user response:

The odd integer constants in the OP code don't make a lot of sense (even if they might work.)

One variable counting up while another counts down can be a bit like Zero Mostel's "One long staircase just going up, and one even longer coming down.." Hard to envision.

Try the following:

#include <stdio.h>

int main() {
    for( int r = 1; r < 7; r   ) { // output 6 rows
        for( int b = r; b <= 7; b   ) // 1=>7, then 2=>7, then 3=>7... easy!
            putchar( 'B' ); // no need to engage all of printf() for a character
        putchar( '\n' );
    }

    return 0;
}
BBBBBBB
BBBBBB
BBBBB
BBBB
BBB
BB

In essence, one can imagine that the floor (the starting point) gets progressively higher, but the ceiling does not move.


Noticed that you ask, in the comments below your question, "What is the correct, efficient way...? "
Here is one way that does not use nested loops:

int main() {
    char *bees = "BBBBBBB";

    for( int i = 0; bees[i 1]; i   ) // " 1" because pattern ends with "BB"
        puts( bees   i );

    return 0;
}

CodePudding user response:

It is much easier if you use functions and can test it with different numbers.

void printPattern(unsigned nrows)
{
    for(unsigned row = nrows; row > 0; row--)
    {
        for(unsigned col = 0; col <= row; col  )
            printf("B");
    printf("\n");
    }
}


int main()
{
    printPattern(7);
    printf("---------------------\n");
    printPattern(3);
    printf("---------------------\n");
    printPattern(1);
    printf("---------------------\n");
    printPattern(0);
    printf("---------------------\n");
    printPattern(15);
    printf("---------------------\n");
}

https://godbolt.org/z/xjzMPczPE

  • Related