C program to print box number pattern with plus in center

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

Example:
Input rows: 5
Input columns: 5
Output:
11011
11011
00000
11011
11011

Required knowledge

Basic C programming, Loop

Logic to print box number pattern with plus in center

Before we move on to this number pattern basic knowledge of printing box number pattern is recommended.

After you are done with the basic box number pattern you can easily get the logic of this pattern. If you look to the pattern carefully, you will notice that the central plus only gets printed if the current column or row is central column, row. Hence before printing 1 inside the inner loop we have to check a condition that if the current row, column is central row, column if so then print 0 instead of 1.

Program to print box number pattern with plus in center

/**
 * C program to print box number pattern with plus in center
 */

#include <stdio.h>

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

    /*
     * Reads number of rows, columns to be printed
     */
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    printf("Enter number of columns: ");
    scanf("%d", &cols);

    centerRow = (rows+1)/2;
    centerCol = (cols+1)/2;

    for(i=1; i<=rows; i++)
    {
        for(j=1; j<=cols; j++)
        {
            //Print 0 for central rows or columns
            if(centerCol == j || centerRow == i)
            {
                printf("0");
            }
            else if((cols%2 == 0 && centerCol+1 == j) || (rows%2 == 0 && centerRow+1 == i))
            {
                //Print an extra 0 for even rows or columns
                printf("0");
            }
            else
            {
                printf("1");
            }
        }

        printf("\n");
    }

    return 0;
}


Output
Enter number of rows: 5
Enter number of columns: 5
11011
11011
00000
11011
11011


Screenshot

C program to print box number pattern with plus in center


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