Number pattern 15 in C

Write a C program to print the given number pattern using for 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

Input rows: 5
Input columns: 5

Output

12345
23451
34521
45321
54321

Required knowledge

Basic C programming, Loop

Logic to print the given pattern

Before you get into this pattern it is highly recommended that you must learn some basic of number pattern printing.

Once you get acquainted with basics number pattern printing, take a minute and have a close eye on this pattern. If you can notice you might divide this entire pattern in two patterns. Let me show.

After looking on both patterns separately I assume that you can easily decode the logic of these two patterns and can combine in single logic. If not here’s what you need to do.

  1. Run an outer loop from 1 to rows (where rows is the total rows to be printed).
  2. To print the first part, run an inner loop from current row to columns. Inside this loop print the current column number.
  3. To print the second part, run another inner loop from current row-1 to 1. Inside this loop again print the current column number.

And you are done. Lets implement this now…

Program to print the given pattern

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

#include <stdio.h>

int main()
{
    int rows, cols, i, j;

    /* Input rows and columns from user */
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    printf("Enter number of columns: ");
    scanf("%d", &cols);

    for(i=1; i<=rows; i++)
    {
        for(j=i; j<=cols; j++)
        {
            printf("%d", j);
        }

        for(j=i-1; j>=1; j--)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}

Output

Enter number of rows: 5
Enter number of columns: 5
12345
23451
34521
45321
54321

Happy coding 😉