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.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, Loop

Logic to print the given square number pattern

Before you learn the logic of the given pattern, you must first learn some basic number pattern.

Now, once you get acquainted with the basic number patterns. 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++)
    {
        // Prints first part of the pattern
        for(j=i; j<=N; j++)
        {
            printf("%d ", j);
        }

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

        printf("\n");
    }

    return 0;
}


Output
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


Screenshot

Square number pattern in C


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