C program to print box number pattern with 1 and 0
11111
10001
10001
10001
11111
C Programming Language / Loop control in C Language
5414Program:
/** * C program to print box number pattern of 1's and 0's * www.atnyla.com */ #include int main() { int rows, cols, i, j; /* Input rows and columns from user */ 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 11111 10001 10001 10001 11111
Explanation:
Required knowledge
Basic C programming, Loop
Logic to print box number pattern
If you look carefully to this pattern you will find that 1 is printed for.
- Every column of the first and last row.
- Start and end column of each row.
Below is the step by step descriptive logic to print the given pattern.
- Input number of rows and columns to print from user. Store it in some variable say rows and cols.
- To iterate through rows run an outer loop from 1 to rows. The loop structure should look like for(i=1; i<=rows; i++).
- To iterate through columns run an inner loop from 1 to cols. The loop structure should look like for(j=1; j<=cols; j++).
- Inside the inner loop before printing 1 check the above mentioned condition. Which is if(i==1 || i==rows || j==1 || j==cols) then print 1 otherwise 0.
- Finally, move to the next line after printing all columns of a row.
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. You can further play with the given pattern to print
11111 1 1 1 1 1 1 11111
To print above pattern you just need to change single line in the above program. Replace the inner printf("0"); with printf(" ");
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.