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 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)
        {
            // Prints numbers for odd row
            for(j=1; j<=i; j++)
            {
                printf("%d", j);
            }
        }
        else
        {
            // Prints 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


Screenshot

Number pattern in C


Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment