11111 00000 11111 00000 11111
/**
* C program to print number pattern of 1, 0 at even/odd rows
*/
#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++)
{
printf("%d", (i%2));
}
printf("\n");
}
return 0;
}
Enter number of rows: 5
Enter number of columns: 5
11111
00000
11111
00000
11111
The previous method if fine and easy to understand. However, you can further optimize the above program. i%2 returns 1 in case of odd and 0 in case of even. Hence, you can remove the if else checking condition. The whole if else condition can be transformed to single printf("%d", (i%2));
Basic C programming, Loop
Must know - Program to print square rectangle number pattern
If you look at the pattern carefully you will notice that for all odd rows 1 is printed and for even rows 0 is printed. Hence, before printing numbers inside inner loop, you need to check even odd condition. If the current row is odd then print 1 otherwise 0.
Below is the step by step descriptive logic to print 1, 0 number pattern at alternate rows.
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.