Triangle number pattern using 0, 1 in C – 4

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

Example

Input

Input N: 5

Output

Required knowledge

Basic C programming, If else, Loop

Logic to print the given number pattern

If you are going through my previous number pattern posts, then I hope that logic of this wouldn’t be difficult. If still its difficult for you to get the logic. Then, read it below else continue to the program.

  1. The pattern consists of N rows (where N is the number of rows to be printed). Outer loop formation to iterate through the rows will be for(i=1; i<=N; i++).
  2. Each row contains exactly i columns (where i is the current row number). Hence the loop formation to iterate though individual columns will be for(j=1; j<=i; j++).
  3. Now comes the logic to print 0 or 1. You can see that 1 only gets printed for first and last column or first and last row otherwise 0 gets printed. Therefore you must check a condition that if(i==1 || i==N || j==1 || j==i) then print 1 otherwise print 0.

Program to print the given number pattern

/**
 * C program to print triangle 0, 1 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++)
        {
            if(i==1 || i==N || j==1 || j==i)
            {
                printf("1");
            }
            else
            {
                printf("0");
            }
        }

        printf("\n");
    }

    return 0;
}

Output

Enter N: 5
1
11
101
1001
11111

Happy coding 😉