10101 10101 10101 10101 10101
/**
* C program to print number pattern with 1/0 at even/odd position
* www.atnyla.com
*/
#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", !(j%2));
}
printf("\n");
}
return 0;
}
Enter number of rows: 5
Enter number of columns: 5
10101
10101
10101
10101
10101
The above method is easy to understand and write. However, you can further optimize the previous method by removing the if else condition. The statement j%2 returns 0 if number is even otherwise returns 1. We only need to print complement of value returned by j%2.
Basic C programming, Loop
Must know - Program to check even number
In previous post I explained a similar pattern. Logic to print this is almost similar. If you have noticed the pattern carefully, for every odd columns 0 is printed and for every even columns 1 is printed.
Below is the step by step descriptive logic to print the given pattern.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.