C program to print chessboard number pattern with 1 and 0
10101
01010
10101
01010
10101
C Programming Language / Loop control in C Language
12470Program:
/** * C program to print box number pattern with cross center * www.atnyla.com */ #include 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
Output:
Enter number of rows: 5 Enter number of columns: 5 10101 01010 10101 01010 10101
Explanation:
Required knowledge
Basic C programming, Loop
Logic to print chessboard number pattern
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.
- Input number of rows and columns to print from user. Store it in some variable say rows and cols.
- Initialize a variable to keep track of alternate element, say k = 1.
- To iterate through rows run an outer loop from 1 to rows. The loop structure should look like for(i=1; i<=rows; i++).
- To iterate through columns run an inner loop from 1 to cols. The loop structure should look like for(j=1; j<=cols; j++).
- Inside the inner loop print 1, 0 for alternate elements. Say if(k == 1) then print 1 otherwise 0. After printing change the value of k = k * -1.
- Finally, move to next line after printing all columns of a row.
This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.
# C Tutorials
# JAVA Tutorials
# HTML Tutorials
# Computer Fundamental
# Data Structure
# DBMS Tutorials
SQL
# C# Language
# R Language
# PHP
# Python
# Vue JS