Number pattern 43 in C

Write a C program to print the given 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 number pattern

Logic to print the given pattern might look complicated at first sight. Take your time and think about any special pattern about the given number series. You might notice following interesting things about the pattern.

  1. It contains total 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. If you notice about the integers printed in each column. They are in increasing order with increasing difference. The difference between first two integers is 1 followed by a difference of 2, 3, 4, 5 and so on.

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

Program to print the given number pattern

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

#include <stdio.h>

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

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

    diff = 1;
    value = 1;

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

            value += diff; // Computes the next value to be printed
            diff++;        // Increments the difference
        }

        printf("\n");
    }

    return 0;
}

Output

Enter rows: 5
1
2  4
7  11 16
22 29 37 46
56 67 79 92 106

Happy coding 😉