Home > Software engineering >  Draw a n x n square but with a special rule
Draw a n x n square but with a special rule

Time:10-30

Given two number N and K, output three squares with the size N x N each with their own set of rules: The first square is made entirely using the '#' symbol. The second square is made using the '.' symbol except for every k rows use the'#' symbol instead. The third square is made using the '.' symbol except for every k columns use the '#' symbol instead/ Also print new line after printing each square.

I already know how to draw a square/shape(Hollowed or filled), but I'm still struggling with this one. Need help for the coding in C language. Thank you!

CodePudding user response:

Here's a hint. Your basic "print me a square structure of size N x N" is normally like this:

for (int row = 0; row < N; row  ) {
    for (int col = 0; col < N; col  ) {
           char c = '#';
           printf("%c",c);
    }
    printf("\n");
}

Now what can you do to modify the code to take into account a different character should be printed for every Kth column or row?

Here's another hint. To decide if row was a Kth row or not, you'd probably use this expression to test:

if (((row 1) % K) == 0)

The 1 takes in account that the loop counting starts at 0 instead of 1.

CodePudding user response:

#include <stdio.h>
#include <string.h>

int main(void) {
    int n = 10;
    int k = 3;
    char b[n];
    char s[n];

    ((char*)memset(b, '#', n-1))[n-1]=0;
    ((char*)memset(s, '.', n-1))[n-1]=0;
    
    for(int i=0; i<n;   i)
    {
        printf("%s\n", (i 1)%k? b : s);
    }
    
    return 0;
}

Output:

Success #stdin #stdout 0s 5452KB
#########
#########
.........
#########
#########
.........
#########
#########
.........
#########

The matrix is 10x10, and every 3rd line is drawn with . instead of #.

  •  Tags:  
  • c
  • Related