Tag Archives: Number Patterns

Half diamond number pattern with star border program in C – 1

Write a C program to print the given half diamond star number pattern series using for loop. How to print the given half diamond star number pattern series using loop in C programming. Logic to print the given star number pattern series using for loop.

Continue reading Half diamond number pattern with star border program in C – 1

Half diamond number pattern program in C – 3

Write a C program to print the given half diamond number pattern series using loop. How to print the given number pattern series using for loop in C programming. Logic to print the given half diamond number pattern series using for loop.

Continue reading Half diamond number pattern program in C – 3

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

Input N: 5

Output

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);
        }

        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

Happy coding 😉