Home > Software design >  Pattern problem in C programming language
Pattern problem in C programming language

Time:06-20

I have the following pattern to print in the C programming language.

BBBB
BAAB
BAAB
BBBB

I have tried the following code, but it's not working.

My code :

#include <stdio.h>

int main() {
    // Write C code here
    int i,j;
    for(i=1;i<=4;i  )
        {
            for(j=1;j<=4;j  )
                {
                    if ((i==1&&j>=i)||(i==4&&j<=i)){
                        printf("%c",65 1);
                    }
                        
                
                    else{
                        printf("%c",65);
                }        
            }
        printf("\n");            
        }        
    return 0;
}

However, the pattern I am getting is the following.

BBBB
AAAA
AAAA
BBBB

CodePudding user response:

The problem with your code is your special case will only fire on the first and fourth row. We can see this a little better if we space things out.

if( 
  (i==1 && j>=i) ||  // `i==1` only on the first row
  (i==4 && j<=i)     // `i==4` only on the fourth row
) {
  printf("%c",65 1);
}

Every other iteration will use your else block that just prints A.

else {
  printf("%c",65);
} 

Note: 'A' is much easier to read than 65, and 'B' much easier than 65 1.


There's plenty of ways to do this. Here's one elegant way with a single loop.

We can observe that we want to print BBBB at the start and every third row. If we start iterating at 0 we can do this when i is divisible by 3. 0/3 has a remainder of 0. 3/3 has a remainder of 0. We use the modulus operator % to get the remainder.

for(int i = 0; i < 4; i  ) {
  if( i % 3 == 0 ) {
    puts("BBBB");
  }
  else {
    puts("BAAB");
  }
}

This will continue to repeat the pattern if you extend the loop. 6/3 has a remainder of 0. 9/3 has a remainder of 0. And so on.

(You could also start with i=1 and check i%3 == 1, but get used to starting counting at 0; it makes a lot of things easier.)

  • Related