c

Printing A Pattern in C


I am a beginner in programming, I studied all about C, I started to solve problems from hackerrank.com, there I faced a problem to print a pattern like given below (the output of problem program):

4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4

the input will be an integer which will provide the data for the length of pattern square, here it is 4 in image, I tried a lot to type a proper logic and I end up with this useless code bellow:

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

int main()
{
    int n;
    scanf("%d", &n);
    
    int array[n- 1 + n][n - 1 + n];
    array[(n - 1 + n) / 2][(n - 1 + n) / 2] = 1;
    int f[n];
    for(int i = 0; i < n; i++) {
        f[i] = i;
    }
    
    for(int i = 0; i < n - 1 + n; i++) {
        for(int j = 0; j < n - 1 + n; j++) {
            array[j][i] = n - f[j];                    //top
            array[i][j] = n - f[j];                    //left
            array[(2 * n - 1 - 1) - i][j] = n - f[i];  //bottem
            array[j][(2 * n - 1 - 1) - i] = n - f[i];  //rigth
        }
    }

    for(int i = 0; i < n - 1 + n; i++) {
        for(int j = 0; j < n - 1 + n; j++) {
            printf("%d ", array[i][j]);
        }
        printf("\n");
    }

    return 0;
}

my logic was to make all four borders correct in for loop which will end at center, but its not working, I want a new logic or to improve my logic, if you want to help me out then please give me the way to solve problem instead of giving me a direct code.


Solution

  • It is observable that the pattern consists of n stacked squares:

    Implementing the above:

    void draw_pattern(const size_t n)
    {
        const size_t dim = 2*n-1;
        int array[dim][dim];
    
        for (size_t i = 0; i < n; ++i) { // Outer square #i
            // Row #0 of the outer square #i
            for (size_t j = i; j < dim-i; ++j)
                array[i][j] = n-i;
                
            // Row #n-1 of the outer square #i
            for (size_t j = i; j < dim-i; ++j)
                array[dim-i-1][j] = n-i;
            
            // Col #0 of the outer square #i
            for (size_t j = i; j < dim-i; ++j)
                array[j][i] = n-i;
            
            // Col #n-1 of the outer square #i
            for (size_t j = i; j < dim-i; ++j)
                array[j][dim-i-1] = n-i;
        }
        
        print_array(dim, array);
    }
    

    This is print_array():

    void print_array(const size_t dim, int array[dim][dim])
    {
        for (size_t i = 0; i < dim; ++i) {
            for(size_t j = 0; j < dim; ++j)
                printf("%d ", array[i][j]);
            
            printf("\n");
        }
    }
    

    Output:

    4 4 4 4 4 4 4
    4 3 3 3 3 3 4
    4 3 2 2 2 3 4
    4 3 2 1 2 3 4
    4 3 2 2 2 3 4
    4 3 3 3 3 3 4
    4 4 4 4 4 4 4
    

    The worst case time complexity is O(n2).