Quantcast
Channel: Codeforwin
Viewing all articles
Browse latest Browse all 132

Triangle number pattern using 0, 1 in C - 2

$
0
0
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.

Example:
Input N: 5
Output:

Required knowledge

Basic C programming, If else, Loop, Even odd logic

Logic to print the given triangle number pattern

  1. 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++).
  2. 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++).
  3. 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.



/**
* 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;
}


Screenshot

Triangle number pattern in c


NOTE: You can also get the below pattern with the same logic What you need to do is. Swap the two print() statements. Replace the printf("1"); with printf("0"); and vice versa.


Happy coding ;)



Viewing all articles
Browse latest Browse all 132

Trending Articles