Example:
Input rows: 5
Input columns: 5
Output:
11111 11111 11011 11111 11111
Required knowledge
Basic C programming, LoopLogic to print box number pattern
On first go you may feel this pattern similar to the previous box number pattern, before you continue to this number pattern please do go through the previous number pattern since it is similar to this.Now, if you carefully look to the pattern you will notice that 0's only gets printed in one of the following conditions:
- If the current row and column are center row and column.
- If rows are even then if the current row is center row+1 and current column is center column or center column+1 (if columns are even).
- If columns are even then if the current column is center column+1 and current row is center row or center row+1 (if rows are even).
Program to print box number pattern of 1's with 0 center
/** * C program to print box number pattern of 1's with 0 as center */ #include <stdio.h> int main() { int rows, cols, i, j; int centerRow, centerCol; /* * Reads number of rows, columns to be printed */ printf("Enter number of rows: "); scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d", &cols); centerRow = (rows+1)/2; centerCol = (cols+1)/2; for(i=1; i<=rows; i++) { for(j=1; j<=cols; j++) { if(centerCol == j && centerRow == i) { printf("0"); } else if(cols%2 == 0 && centerCol+1 == j) { if(centerRow == i || (rows%2 == 0 && centerRow+1 == i)) printf("0"); else printf("1"); } else if(rows%2 == 0 && centerRow+1 == i) { if(centerCol == j || (cols%2 == 0 && centerCol+1 == j)) printf("0"); else printf("1"); } else { printf("1"); } } printf("\n"); } return 0; }
Output
Enter number of rows: 5
Enter number of columns: 5
Enter number of columns: 5
11111 11111 11011 11111 11111
Screenshot
Happy coding ;)