Example:
Input rows: 5
Input columns: 5
Output:
Required knowledge
Basic C programming, LoopLogic to print box number pattern
Before moving on to this number pattern I highly recommend you to go through some previous number pattern to get yourself familiar about printing number patterns.Now, talking about this pattern if you look carefully to this pattern you will see that 1's are printed in below two conditions:
- 1's are printed for each column for the first and last row.
- 1's are printed at the start and end of each column.
Program to print box number pattern of 1's and 0's
/** * C program to print box number pattern of 1's and 0's */ #include <stdio.h> int main() { int rows, cols, i, j; /* * Reads number of rows, columns to be printed */ printf("Enter number of rows: "); scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d", &cols); for(i=1; i<=rows; i++) { for(j=1; j<=cols; j++) { //Print 1 if its first or last row //Print 1 if its first or last column if(i==1 || i==rows || j==1 || j==cols) { printf("1"); } else { printf("0"); } } printf("\n"); } return 0; }
Output
Enter number of rows: 5
Enter number of columns: 5
Enter number of columns: 5
11111 10001 10001 10001 11111
Note: You can also reverse the given number pattern with 0's as border and 1's at the center. For that you just need to swap the inner two printf("1"); with printf("0"); statement.
Screenshot
Now you can twist with this program to generate this pattern. To print above pattern you just need to change single line in the above program. You just need to replace the inner printf("0"); with printf(" ");.
Program to print box number pattern
/** * C program to print box number pattern of 1's and 0's */ #include <stdio.h> int main() { int rows, cols, i, j; /* * Reads number of rows, columns to be printed */ printf("Enter number of rows: "); scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d", &cols); for(i=1; i<=rows; i++) { for(j=1; j<=cols; j++) { //Print 1 if its first or last row //Print 1 if its first or last column if(i==1 || i==rows || j==1 || j==cols) { printf("1"); } else { printf(" "); } } printf("\n"); } return 0; }
Screenshot
Happy coding ;)