Hollow square number pattern 1 in C

Write a C program to print the given number pattern using for loop. How to print the given hollow square number pattern using loop in C programming. Logic to print the given number pattern using loop in C program.

Example

Input

Input N: 5

Output

Required knowledge

Basic C programming, Loop

Logic to print the given number pattern

Before you continue to this pattern, I recommend you to learn some basic number pattern. As it will help you grasp the logic quicker.

Once you get familiar with some basic number patterns. Lets learn logic to print the given pattern.

If you are following my previous posts then you might have noticed that this pattern is almost similar to the previous number pattern. I recommend you to go through the previous number pattern before you move on to this pattern. As logic of this pattern is same as previous pattern.

There can be many logic to print the given pattern. Here I am discussing the easiest way to print the given pattern. First to make things easier lets divide the pattern in two parts.

Logic to print the given number pattern is:

  1. The pattern consists of N rows (where N is the number of rows to be printed). Hence the outer loop formation is for(i=1; i<=N; i++).
  2. To print the first part of the pattern run an inner loop from i to N (where i is the current row number). Hence the loop formation will be for(j=i; j<=N; j++). Inside this loop print the current value j.
  3. To print the second part of the pattern. Initialize a variable k = j - 2. After that run another inner loop from 1 to i-1. Loop formation for this will be for(j=1; j<i; j++, k--). Inside this loop print the current value of k.
  4. Note: Numbers only gets printed for first and last row or column otherwise spaces gets printed.

Lets not implement this on code.

Program to print hollow square number pattern

/**
 * C program to print given number pattern
 */

#include <stdio.h>

int main()
{
    int i, j, N;
    int k = 1;

    printf("Enter N: ");
    scanf("%d", &N);

    for(i=1; i<=N; i++)
    {
        // Print first part of the pattern
        for(j=i; j<=N; j++)
        {
            if(i==1 || i==N || j==i)
                printf("%d", j);
            else
                printf(" ");
        }

        // Print second part of the pattern
        k = j - 2;
        for(j=1; j<i; j++, k--)
        {
            if(i==1 || i==N || j==i-1)
                printf("%d", k);
            else
                printf(" ");
        }

        printf("\n");
    }

    return 0;
}

Output

Enter N: 5
12345
2   4
3   3
4   2
54321

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>