Number pattern 26 in C

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

Example

Input

Input N: 5

Output

Required knowledge

Basic C programming, Loop

Logic to print the given number pattern 1

The above pattern consists of N rows (where N is the total rows to be printed). To since the pattern is in descending order hence, to make things easier we will iterate through rows from N-1 instead of 1-N so now the first row is row5, second row is row4 and last row is row1. Each row contains exactly i columns (where i is the current row number).
The step-by-step descriptive logic of the pattern is:

  1. To iterate through rows, run an outer loop from N to 1 in decreasing order.
  2. To print the columns, run an inner loop from i to 1 in decreasing order. Inside this loop print the value of j (where j is the current column number).

Lets, code it.

Program to print the given number pattern 1

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

#include <stdio.h>

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

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

    for(i=N; i>=1; i--)
    {
        // Logic to print numbers
        for(j=i; j>=1; j--)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}

Output

Enter N: 5
54321
4321
321
21
1

Logic to print the given number pattern 2

If you look to the above pattern you will find that the logic to print the numbers are similar as the first pattern. Hence, we only need to write the logic to print the trailing spaces that gets printed before the number. You can hover on to the pattern to see or count the number of spaces per row. Total number of spaces per row is N – i (where N is the total number of rows and i is the current row number). Note that i loops in decreasing order i.e. at row1 i=5, at row2 i=4 and so on.
Step-by-step descriptive logic to print spaces:

  1. To print spaces, run an inner loop from i to N – 1. Inside this loop print the value of j (where j is the current column number).

Lets implement the logic.

Program to print the given number pattern 2

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

#include <stdio.h>

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

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

    for(i=N; i>=1; i--)
    {
        // Logic to print spaces
        for(j=i; j<=N-1; j++)
        {
            printf(" ");
        }

        // Logic to print numbers
        for(j=i; j>=1; j--)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}

Happy coding 😉