C program to print box number pattern with 1 and 0

Write a C program to print the given box number pattern with 1's and 0's using loop. How to print box number pattern using one's and zero's using for loop in C programming. Logic to print box number pattern with 1's as border and 0's at center in C program.

Example

Input

Input rows: 5
Input columns: 5

Output

11111
10001
10001
10001
11111

Required knowledge

Basic C programming, Loop

Logic to print box number pattern

If you look carefully to this pattern you will find that 1 is printed for.

  • Every column of first and last row.
  • Start and end column of each row.

Below is the step by step descriptive logic to print the given 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 through columns run an inner loop from 1 to cols. The loop structure should look like for(j=1; j<=cols; j++).
  4. Inside the inner loop before printing 1 check the above mentioned condition. Which is if(i==1 || i==rows || j==1 || j==cols) then print 1 otherwise 0.
  5. Finally, move to the next line after printing all columns of a row.

Program to print box number pattern of 1s and 0s

/**
 * C program to print box number pattern of 1's and 0's
 */

#include <stdio.h>

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

    /* Input rows and columns from user */
    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++)
        {
            /* 
             * Print 1 if its first or last row
             * Print 1 if its first or last column
             */
            if(i==1 || i==rows || j==1 || j==cols)
            {
                printf("1");
            }
            else
            {
                printf("0");
            }
        }

        printf("\n");
    }

    return 0;
}

Output

Enter number of rows: 5
Enter number of columns: 5
11111
10001
10001
10001
11111

Note: You can also reverse the given number pattern with 0's as border and 1's at the center. For that you just need to swap the inner two printf("1"); with printf("0"); statement. You can further play with the given pattern to print

To print above pattern you just need to change single line in the above program. Replace the inner printf("0"); with printf(" ");

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>