C program to print chessboard number pattern with 1 and 0

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.

Example

Input

Input rows: 5
Input columns: 5

Output

10101
01010
10101
01010
10101

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.

  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.

Program to print chessboard number pattern

/**
 * C program to print box number pattern with cross center
 */

#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

You can play with the above two printf() statements to get following cool patterns.

and many more just change the inner two printf(); statements and enjoy the fun.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>