Number pattern 39 in C

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

Example:
Input N: 5
Output:
1
131
13531
1357531
135797531
    1
   131
  13531
 1357531
135797531


Required knowledge

Basic C programming, Loop

Logic to print the given pattern

1
131
13531
1357531
135797531
When you look to the pattern, it might look similar to the odd number pattern. Logic to the pattern would be very simple if you know how to print odd number pattern.

Now, lets have a quick look on to the pattern. The following observations can be made about the pattern.
  1. It consists of N rows (where N is the total number of rows to be printed).
  2. To make things little easier you can internally divide the pattern in two parts.
  3. The first part is completely odd number pattern and the loop structure to print the given pattern is for(j=1; j<=(i*2) - 1; j++).
  4. The second part is also an odd pattern in decreasing order. The loop structure to print the second part will be for(j=(i-1)*2-1; j>=1; j--).
Now, what we need to do is combine the logic of both programs into single program.

Program to print the given pattern

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

#include <stdio.h>

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

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

    for(i=1; i<=N; i++)
    {
        // Prints the first part of pattern
        for(j=1; j<=(i*2)-1; j+=2)
        {
            printf("%d", j);
        }

        // Prints the second part of pattern
        for(j=(i-1)*2-1; j>=1; j-=2)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}


Output
Enter rows: 5
1
131
13531
1357531
135797531


Screenshot

Number pattern program in C


Now, once you got the logic to print this pattern you can easily print the second pattern. You just need to add extra spaces at the beginning.
    1
   131
  13531
 1357531
135797531


Program to print the above pattern

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

#include <stdio.h>

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

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

    for(i=1; i<=N; i++)
    {
        // Prints space
        for(j=i; j<N; j++)
        {
            printf(" ");
        }

        // Prints first part of the pattern
        for(j=1; j<=(i*2)-1; j+=2)
        {
            printf("%d", j);
        }

        // Prints second part of the pattern
        for(j=(i-1)*2-1; j>=1; j-=2)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    scanf("%d", &i);

    return 0;
}


Screenshot

Number pattern program in C


Happy coding ;)


You may also like

Labels: , , ,