Number pattern 44 in C

Write a C program to print the given triangular number pattern using for loop. How to print the given 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 pattern

To get the logic of the pattern given above have a close look to the pattern for a minute. You can easily note following points about the pattern.

  1. The pattern 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. Now, talking about the numbers printed. They are printed in a special order i.e. for each odd row numbers are printed in ascending order and for even rows they are printed in descending order.
  4. For odd row first column value start at total_numbers_printed + 1 (where total_numbers_printed is the total numbers printed till current row, column).
  5. For even row first column value start at total_numbers_printed + i.

Based on the above logic lets write down the code to print the pattern.

Program to print the given pattern

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

#include <stdio.h>

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

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

    count = 0;

    for(i=1; i<=N; i++)
    {
        // Starting value of column based on even or odd row.
        value = (i & 1) ? (count + 1) : (count + i);

        for(j=1; j<=i; j++)
        {
            printf("%-3d", value);

            // Increment the value for odd rows
            if(i & 1)
                value++;
            else
                value--;

            count++;
        }

        printf("\n");
    }

    return 0;
}

Output

Enter rows: 5
1
3  2
4  5  6
10 9  8  7
11 12 13 14 15

Happy coding 😉