×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to print box pattern using loops

Here, we are going to implement a C program to print a box pattern of the numbers using loops.
Submitted by Bhawna Aggarwal, on May 30, 2019

Problem statement

Input a number and print the following box pattern in C language,

4 4 4 4 4 4 4
4 3 3 3 3 3 4   
4 3 2 2 2 3 4   
4 3 2 1 2 3 4   
4 3 2 2 2 3 4   
4 3 3 3 3 3 4   
4 4 4 4 4 4 4   

Input format

The input will contain a single integer.

Constraints

1<=n>=100

Output format

Print the pattern mentioned in the problem statement.

Example

Input:
2

Output:
2 2 2 
2 1 2 
2 2 2

Code to print the box pattern in C

//Code to print the box pattern in C
#include <stdio.h>

int main()
{
    int n, i, j, t; //n is representing number of the output box

    //input n
    printf("Enter the value of n: ");
    scanf("%d", &n);

    t = 2 * n - 1;
    i = t; //i and j are the number of rows and columns of the box.
    j = t;

    // Declare box as a 2-D matrix having i number of rows 
	//and j number of columns
    int a[i][j], k, m, p;
    p = n;
    m = 0;

    for (k = 0; k < p; k++) {
        for (i = m; i < t; i++) {
            for (j = m; j < t; j++) {
                if (i == m || i == (t - 1) || j == m || j == (t - 1)) {
                    a[i][j] = n;
                    if (n == 1) {
                        break;
                    }
                }
            }
        }
        t = t - 1;
        n = n - 1;
        m = m + 1;
    }
    t = 2 * m - 1;
    for (i = 0; i < t; i++) {
        for (j = 0; j < t; j++) {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output

First run:
Enter the value of n: 2 
2 2 2 
2 1 2 
2 2 2

Second run:
Enter the value of n: 4  
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4  

C Pattern Printing Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.