11011 11011 00000 11011 11011
/**
* C program to print box number pattern with plus in center
* www.atnyla.com
*/
#include <stdio.h>
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);
centerRow = (rows+1) / 2;
centerCol = (cols+1) / 2;
for(i=1; i<=rows; i++)
{
for(j=1; j<=cols; j++)
{
// Print 0 for central rows or columns
if(centerCol == j || centerRow == i)
{
printf("0");
}
else if((cols%2 == 0 && centerCol+1 == j) || (rows%2 == 0 && centerRow+1 == i))
{
// Print an extra 0 for even rows or columns
printf("0");
}
else
{
printf("1");
}
}
printf("\n");
}
return 0;
}
Output
Enter number of rows: 5
Enter number of columns: 5
11011
11011
00000
11011
11011
Basic C programming, Loop
Before I get to formal descriptive logic of the pattern, have a close look at the given pattern. You will notice that 0 is printed for central columns or rows i.e. 0 is printed for all cols / 2 and rows / 2.
Below is the step by step descriptive logic to print the given number pattern.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.