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 with 0, 1 in C program.
Required knowledge
Basic C programming, If else, Loop
Logic to print the given triangle number pattern
- The pattern consists of N rows (where N is the total number of rows to be printed). Hence the outer loop formation to iterate through rows will be for(i=1; i<=N; i++).
- Each row contains exactly i number of columns (where i is the current row number) i.e. first row contains 1 column, 2 row contains 2 column and so on.
Hence the inner loop formation to iterate through columns will be for(j=1; j<=i; j++). - Once you are done with the loop semantics, you just need to print the number. If you notice the numbers are in special order. For each odd rows 1 gets printed and for each even rows 0 gets printed. Now to implement this we need to check a simple condition if(i % 2 == 1) before printing 1s or 0s.
Lets, now implement this in C program.
Program to print given triangle 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++)
{
// Print 1s for every odd rows
if(i % 2 == 1)
{
printf("1");
}
else
{
printf("0");
}
}
printf("\n");
}
return 0;
}
Output
Enter N: 5 1 00 111 0000 11111
You can also print this pattern without using if else. Below is a tricky approach to print the given number pattern without using if else. It uses bitwise operator to check even odd.
Program to print the given number pattern without using if
/**
* 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", (i & 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 😉