Number Patterns
C program to print box number pattern of 1 and 0 with cross center
Write a C program to print the given number pattern of 1's and 0's with cross in the center using loop. How to print box number pattern of 1, 0 with X in center using loop in C programming. Logic to print box number pattern with cross center using loop in C program.
Example
Input
Input rows: 5
Input columns: 5
Output
10001 01010 00100 01010 10001
Required knowledge
Basic C programming, Loop
Logic to print box number pattern with cross center
In the given pattern, 1 is printed only when -
->Current column equals to current row.
->Current column equals (total columns + 1) - current row.
Below is the step by step descriptive logic to print the given number pattern.
1.Input number of rows and columns to print from user. Store it in some variable say rows and cols.
2.To iterate through rows run an outer loop from 1 to rows. The loop structure should look like for(i=1; i<=rows; i++).
3.To iterate through columns run an inner loop from 1 to cols. The loop structure should look like for(j=1; j<=cols; j++).
4.Inside the inner loop check if(i == j || (j == (cols+1)-i)) then print 1 otherwise print 0.
5.Finally, move to the next line after printing all columns of a row.
Program to print box number pattern with cross center
/** * C program to print box number pattern with cross center */ #include <stdio.h> 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++) { if(i == j || (j == (cols+1) - i)) { printf("1"); } else { printf("0"); } } printf("\n"); } return 0; }
Output
Enter number of rows: 5
Enter number of columns: 5
10001 01010 00100 01010 10001
Fun with patterns: To have more fun with these patterns just change the character which you want to print i.e. the inner two printf(); statements and get the following patterns like mentioned below.
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1111111 1 11111 1 11 111 11 111 1 111 1111 1111 111 1 111 11 111 11 1 11111 1 1111111
X X X X X X X X X X X X X X X X X
X-------X -X-----X- --X---X-- ---X-X--- ----X---- ---X-X--- --X---X-- -X-----X- X-------X
and many more just change the inner two printf(); statements.