10101 01010 10101 01010 10101
/**
* C program to print box number pattern with cross center
* www.atnyla.com
*/
#include <stdio.h>
int main()
{
int rows, cols, i, j, k;
/* Input rows and columns from user */
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);
k = 1;
for(i=1; i<=rows; i++)
{
for(j=1; j<=cols; j++)
{
if(k == 1)
{
printf("1");
}
else
{
printf("0");
}
// If k = 1 then k *= -1 => -1
// If k = -1 then k *= -1 => 1
k *= -1;
}
if(cols % 2 == 0)
{
k *= -1;
}
printf("\n");
}
return 0;
}
Output
Enter number of rows: 5
Enter number of columns: 5
10101
01010
10101
01010
10101
Basic C programming, Loop
If you think the above pattern as a matrix, then 1 and 0 is printed at every alternate element. To keep track of alternate element we will use an extra variable say k. k can have two possible values i.e. -1 and 1. For k = 1 print 1 otherwise print 0.
Below is the step by step descriptive logic to print the given 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.