cloops

Printing Pattern using Loops


I am solving a challenge on hackerrank. It's printing a number in spiral pattern decreasing it's value at each circle completion.

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

//Printing Pattern using Loops
/* for eg. for n = 4 
  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
 */
 //Author: Arvind Bakshi
 #include <stdio.h>
 #include <string.h>
 #include <math.h>
 #include <stdlib.h>

int main() 
{

int n,row,col,size;
scanf("%d", &n);
// Complete the code to print the pattern.
size=2*n-1;
  int arr[size][size];
  //n=n+1;
    while(n>0){
        row=0;
        col=0;
        while(col<size){
          arr[row][col] = n;
          col++;
        }
        col=size-1;
        row=0;
        while(row<size){
            arr[row][col]=n;
            row++;
        }
        row = size-1;
        col = size-1;
        while (col >=0) {
          arr[row][col] = n;
          col--;
        }
        col = 0;
        row = size-1;
        while (row >=0) {
          arr[row][col] = n;
          row--;
        }
        n--;
    }
    for(row=0;row<size;row++){
        for(col=0;col<size;col++){
            printf("%d",arr[row][col]);
        }
        printf("\n");
    }
return 0;
}

Expected output is

 2 2 2 
 2 1 2 
 2 2 2

I am getting

111
101
111

There is numerous code available for it online, I just want to know my mistake, where I am doing wrong. Please don't mark it as a repeat.


Solution

  • Check this code. Online compiler I used your same code with an extra buffer 'x'. This makes the frame to move across the loop in decreasing spiral.

    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    #include <stdlib.h>
    
    int main() 
    {
      int n,row,col,size;
      scanf("%d", &n);
      // Complete the code to print the pattern.
      size=2*n;
      int x = n;
      int arr[size-1][size-1];
      //n=n+1;
      while(n>0){
        row=x-n;
        col=x-n;
        while(col<size-(x-n)-2){
          arr[row][col] = n;
          col++;
        }
        col=size-(x-n)-2;
        row=x-n;
        while(row<size-(x-n)-1){
          arr[row][col]=n;
          row++;
        }
        row = size-(x-n)-2;
        col = size-(x-n)-2;
        while (col >x-n) {
          arr[row][col] = n;
          col--;
        }
        col = x-n;
        row = size-(x-n)-2;
        while (row > x-n) {
          arr[row][col] = n;
          row--;
        }
        n--;
      }
      for(row=0;row<size-1;row++){
        for(col=0;col<size-1;col++){
          printf("%d ",arr[row][col]);
        }
        printf("\n");
      }
      return 0;
    }
    


    These are your expected outputs. for input 2 for input 4