Number pattern 18 in C

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

Example:
Input N: 5
Output:
12345
21234
32123
43212
54321
54321
43212
32123
21234
12345


Required knowledge

Basic C programming, Loop

Logic to print the given number pattern

Before learning the logic of this number pattern, you first must be acquainted with some basic number patterns.

Now, once you are acquainted with some basic logic to print number pattern. If you look to both the patterns you will find both similar to each other. Hence, if you get the logic of one you can easily print the second one. Now lets get into first pattern, take a minute and have a close eye to the below pattern.
12345
21234
32123
43212
54321
If you can notice, you can actually divide this in two parts to make things easier. Let me show.
-----
2----
32---
432--
5432-
12345
-1234
--123
---12
----1
Now you can find that printing these patterns separately is relatively easier than the whole. Below is the logic to print this pattern as a whole.
  1. To iterate through the rows, run an outer loop from 1 to N.
  2. To print the first part of the pattern, run an inner loop from N - current_row + 1 to 1. Inside this loop print the current column number.
  3. To print the second part of the pattern, run another inner loop from 1 to current row. Inside this loop print the value of current column number.
And you are done. Lets implement this on code.

Note: I won't be explaining the logic of second number patterns as both are similar in-fact second pattern is reverse of first. I will be providing source codes of both.


Program to print the given number pattern 1

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

#include <stdio.h>

int main()
{
    int N, i, j;

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

    for(i=1; i<=N; i++)
    {
        //Prints first part
        for(j=i; j>1; j--)
        {
            printf("%d", j);
        }

        //Prints second part
        for(j=1; j<= (N-i +1); j++)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}


Output
Enter N: 5
12345
21234
32123
43212
54321


Screenshot 1

C program to print number pattern


Program to print the given number pattern 2

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

#include <stdio.h>

int main()
{
    int N, i, j;

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

    for(i=1; i<=N; i++)
    {
        //Prints first part
        for(j=(N-i +1); j>1; j--)
        {
            printf("%d", j);
        }

        //Prints second part
        for(j=1; j<=i; j++)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}


Screenshot 2

C program to print number pattern


Happy coding ;)


You may also like

Labels: , , ,