Triangle number pattern using 0, 1 in C – 1

Write a C program to print the given triangle number pattern using 0, 1. How to print triangle number pattern with 0, 1 using for loop in C programming. Logic to print the given triangular number pattern using 0, 1 in C programming.

Example

Input

Input N: 5

Output

Required knowledge

Basic C programming, If else, Loop

Logic to print the given number pattern

To print these type of patterns, the main thing you need to get is the loop formation to iterate over rows and columns. Before I discuss the logic to print the given number pattern. Have a close eye to the pattern. Below is the logic to print the given number pattern.

  1. The pattern consists of total N number of rows (where N is the total number of rows to be printed). Therefore the loop formation to iterate through rows will be for(i=1; i<=N; i++).
  2. Here each row contains exactly i number of columns (where i is the current row number). Hence the inner loop formation to iterate through each columns will be for(j=1; j<=i; j++).
  3. Once you are done with the loop formation to iterate through rows and columns. You need to print the 0’s and 1’s. Notice that here for each odd columns 1 gets printed and for every even columns 0 gets printed. Hence you need to check a simple condition if(j % 2 == 1) before printing 1s or 0s.

Lets, now code it down.

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 N: ");
    scanf("%d", &N);

    for(i=1; i<=N; i++)
    {
        for(j=1; j<=i; j++)
        {
            // For every odd column print 1
            if(j % 2 == 1)
            {
                printf("1");
            }
            else
            {
                printf("0");
            }
        }

        printf("\n");
    }

    return 0;

}

Output

Enter N: 5
1
10
101
1010
10101

Instead of using if else you can also print the pattern using a simple but tricky method. Below is a tricky approach to print the given number pattern without using if else. Below program uses bitwise operator to check even odd, learn how to check even odd using bitwise operator.

Program to print given number pattern without if else

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

#include <stdio.h>

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

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

    for(i=1; i<=N; i++)
    {
        for(j=1; j<=i; j++)
        {
            printf("%d", (j & 1));
        }

        printf("\n");
    }

    return 0;
}

Note: You can also get the below pattern with the same logic

What you need to do is, swap the two printf() statements. Replace the printf(“1”); with printf(“0”); and vice versa.

Happy coding 😉