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 rows: 5
Input columns: 5
Output:
10101
01010
10101
01010
10101

Required knowledge

Basic C programming, Loop

Logic to print chessboard number pattern

Before getting in detail with this pattern I recommend you to go through one of my previous number patterns to get yourself acquainted with the basic logic of number patterns.

Now, once you are done with some number pattern program. Look carefully to the pattern and you will notice that in this pattern 1's and 0's are printed for every alternate columns. Now to do that we need to keep track of what we have printed last, and for that I have used an extra variable k will will help us to differentiate between last and current column. Now, I have assumed that when the value of k=1 then I will print 1 and when it is k= -1 I will print 0. Also we need to change the value of k from 1 to -1 and vice versa each time a column gets printed and to do so I have implemented a logic i.e. k = k * -1 which will swap the value of k from 1 to -1 and vice versa.

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;

    /*
     * Reads number of rows, columns to be printed
     */
    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


Screenshot

C program to print chessboard number pattern


Fun with patterns: You can have more fun with this pattern just change the inner two printf() statements to some other characters and get these patterns.


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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment