C program to print box number pattern of 1 and 0 with cross center

Write a C program to print the given number pattern of 1's and 0's with cross in the center using loop. How to print box number pattern of 1, 0 with X in center using loop in C programming. Logic to print box number pattern with cross center using loop in C program.

Example:
Input rows: 5
Input columns: 5
Output:
10001
01010
00100
01010
10001

Required knowledge

Basic C programming, Loop

Logic to print box number pattern with cross center

Before moving on to this pattern I recommend you to go through the previous number pattern to get yourself acquainted with the number patterns logic.

Now, once you are acquainted with basic of number pattern. If you look to this pattern carefully you will notice a special pattern in which 1's gets printed here. Actually, 1's only gets printed in one of two conditions:
  1. If the current column equals to current row.
  2. If the current column equals (total columns+1) - current row.
Hence, to print the given pattern you just need to check these two conditions and if these satisfies then print 1 otherwise 0.

Program to print box number pattern with cross center

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

#include <stdio.h>

int main()
{
    int rows, cols, i, j;

    /*
     * Reads number of rows, columns to be printed
     */
    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++)
        {
            if(i == j || (j == (cols+1)-i))
            {
                printf("1");
            }
            else
            {
                printf("0");
            }
        }

        printf("\n");
    }

    return 0;
}


Output
Enter number of rows: 5
Enter number of columns: 5
10001
01010
00100
01010
10001


Screenshot

C program to print box number pattern with cross center


Fun with patterns: To have more fun with these patterns just change the character which you want to be printed i.e. the inner two printf(); statements and get the following patterns.

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

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