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

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

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

Required knowledge

Basic C programming, Loop

Logic to print box number pattern

On first go you may feel this pattern similar to the previous box number pattern, before you continue to this number pattern please do go through the previous number pattern since it is similar to this.

Now, if you carefully look to the pattern you will notice that 0's only gets printed in one of the following conditions:
  1. If the current row and column are center row and column.
  2. If rows are even then if the current row is center row+1 and current column is center column or center column+1 (if columns are even).
  3. If columns are even then if the current column is center column+1 and current row is center row or center row+1 (if rows are even).
Other than these conditions 1 gets printed.

Program to print box number pattern of 1's with 0 center

/**
 * C program to print box number pattern of 1's with 0 as 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++)
        {
            if(centerCol == j && centerRow == i)
            {
                printf("0");
            }
            else if(cols%2 == 0 && centerCol+1 == j)
            {
                if(centerRow == i || (rows%2 == 0 && centerRow+1 == i))
                    printf("0");
                else
                    printf("1");
            }
            else if(rows%2 == 0 && centerRow+1 == i)
            {
                if(centerCol == j || (cols%2 == 0 && centerCol+1 == j))
                    printf("0");
                else
                    printf("1");
            }
            else
            {
                printf("1");
            }
        }

        printf("\n");
    }

    return 0;
}


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


Screenshot

C program to print box number pattern of 1 with 0 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