Number pattern 41 in C

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

Example

Input

Input N: 5

Output

Required knowledge

Basic C programming, Loop

Logic to print the given number pattern

To get the logic of the pattern have a close look to the pattern for a minute. You might notice following things about the pattern.

  1. It contains N rows (where N is the total number of rows to be printed).
  2. Each row contains exactly i columns (where i is the current row number).
  3. For all odd rows it contains numbers in increasing order from 1 to i. Hence the inner loop formation to print the odd rows will be for(j=1; j<=i; j++).
  4. For all even rows it contains numbers in decreasing order from i to 1. The inner loop formation to print the even rows will be for(j=i; j>=1; j--).

Based on the above observations lets code down the solution of the pattern.

Program to print the given number 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++)
    {
        if(i & 1)
        {
            // Print numbers for odd row
            for(j=1; j<=i; j++)
            {
                printf("%d", j);
            }
        }
        else
        {
            // Print numbers for even row
            for(j=i; j>=1; j--)
            {
                printf("%d", j);
            }
        }

        printf("\n");
    }

    return 0;
}

Output

Enter rows: 5
1
21
123
4321
12345

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>