Square number pattern 2 in C

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



Input N: 5


Required knowledge

Basic C programming, Loop

Logic to print the given square number pattern

Give a close look to the given number pattern. On first look the pattern may seem difficult to print. To make things easier lets divide the pattern into similar patterns.

Now logic to print these two patterns separately is comparatively easier. These two patterns are also discussed separately my previous posts - Pattern part 1 - Pattern part 2.

Logic to print both of these pattern as a whole:

  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.

And you are done. Lets now, code it down.

Program to print the given 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++)
            printf("%d ", j);

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


    return 0;


Enter N: 5
1 2 3 4 5
2 3 4 5 4
3 4 5 4 3
4 5 4 3 2
5 4 3 2 1

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols. as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>