C program to print box number pattern of 1 with 0 center
11111
11111
11011
11111
11111
C Programming Language / Loop control in C Language
4156Program:
/** * C program to print box number pattern of 1's with 0 as center */ #include int main() { int rows, cols, i, j; int centerRow, centerCol; /* Input rows and columns from user */ printf("Enter number of rows: "); scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d", &cols); /* Find center row and column */ 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 11111 11111 11011 11111 11111
Explanation:
Required knowledge
Basic C programming, Loop
Logic to print box number pattern
11111 11111 11011 11111 11111
In the above given pattern for every row and column 1 is printed except for the center row and column. Hence, to print this pattern we only need to focus on condition of center row and column.
Below is the step by step descriptive logic to print given pattern.
- Input number of rows and columns from user. Store it in some variable say rows and cols.
- Run an outer loop from 1 to rows, to iterate through rows. The loop structure should look like for(i=1; i<=rows; i++).
- Run an inner loop from 1 to cols, to iterate through cols. The loop structure should look like for(j=1; j<=cols; j++).
- Inside the inner before printing any number check the central row and column condition. Which is if(i==rows/2 && j==cols/2) then print 0, otherwise print 1.
- Finally, move to next life after printing all columns of a row.
This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.
# C Tutorials
# JAVA Tutorials
# HTML Tutorials
# Computer Fundamental
# Data Structure
# DBMS Tutorials
SQL
# C# Language
# R Language
# PHP
# Python
# Vue JS