Number pattern 34 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 in C program.

Required knowledge

Basic C programming, Loop

Logic to print the given number pattern 1

Before I discuss about the logic of the given pattern I would recommend you to look to the pattern carefully for a minute to make things easier.
Now, talking about the pattern it consists of N rows (where N is the total number of rows to be printed). Each row consists of exactly i * 2 – 1 columns (where i is the current row number).

Step-by-step descriptive logic:

  1. To iterate though rows, run an outer loop from 1 to N.
  2. To print columns, run an inner loop from 1 to i * 2 – 1 (where i is the current row number). Inside this loop print the value of j (where j is the current column number).

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=1; i<=N; i++)
    {
        // Logic to print numbers
        for(j=1; j<=(i*2-1); j++)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}

Output

Enter N: 5
1
123
12345
1234567
123456789

Logic to print the given number pattern 2

If you look to the pattern, you will find that above pattern is almost similar to the first pattern we just printed. The logic to print numbers will be same as first pattern we did, we only need to add the logic of printing spaces. To see or count total number of spaces per row you can hover on to the pattern. There are (N – i) * 2 spaces each row (where i is the current row number), as the first row contains (5 – 1) * 2 = 8 spaces, and second contains 6 spaces and so on last row contains 0 spaces.

Step-by-step descriptive logic:

  1. To print spaces, run an inner loop from 1 to (N – i) * 2. Inside this loop print single blank space.

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=1; i<=N; i++)
    {
        // Logic to print spaces
        for(j=1; j<= ((N-i)*2); j++)
        {
            printf(" ");
        }

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

        printf("\n");
    }

    return 0;
}

Happy coding 😉