Home / Programs / C program to print chessboard number pattern with 1 and 0 10101 01010 10101 01010 10101
Programming Example

C program to print chessboard number pattern with 1 and 0
10101
01010
10101
01010
10101

👁 12,096 Views
💻 Practical Program
📘 Step by Step Learning
Write a C program to print the given chessboard number pattern of 1's and 0's using loop. How to print chessboard number pattern of n rows and n columns using for loop in C programming. Logic to print chessboard number pattern of n rows and n columns using for loop in C program.

Program Code

/**
 * 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

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 kk 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.

  1. Input number of rows and columns to print from user. Store it in some variable say rows and cols.
  2. Initialize a variable to keep track of alternate element, say k = 1.
  3. To iterate through rows run an outer loop from 1 to rows. The loop structure should look like for(i=1; i<=rows; i++).
  4. To iterate through columns run an inner loop from 1 to cols. The loop structure should look like for(j=1; j<=cols; j++).
  5. 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.
  6. Finally, move to next line after printing all columns of a row.

How to learn from this program

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.