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

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 I get to formal descriptive logic of the pattern, have a close look at the given pattern. You will notice that 0 is printed for central columns or rows i.e. 0 is printed for all cols / 2 and rows / 2.
Below is the step by step descriptive logic to print the given number pattern.

  1. Input number of rows and columns to print from user. Store it in some variable say rows and cols.
  2. To iterate through rows run an outer loop from 1 to rows. The loop structure should look like for(i=1; i<=rows; i++).
  3. To iterate though columns run an inner loop from 1 to cols. The loop structure should look like for(j=1; j<=cols; j++).
  4. We already know that 0 is printed only for central rows and columns otherwise 1 is printed. Hence, if(i == rows/2 || j == cols/2), then print 0 otherwise print 1.
  5. Finally, move to the next line after printing all columns of a row.

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;

    /* Input rows and columns from user */
    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

Happy coding 😉