Example:
Input N: 5
Output:
Required knowledge
Basic C programming, If else, Loop, Even odd logicLogic 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++).
- Here each row contains exactly i number of columns (where i is the current row number). Loop formation to iterate through columns will be for(j=1; j<=i; j++).
- Once you are done with the loop formation. Have a closer look to the pattern. If you view the pattern as you can easily print the final pattern. Where for each odd integers 1 gets printed and for each even integers 0 gets printed. Therefore to get such pattern we need to check a simple condition if(k % 2 == 1) before printing 1s or 0s (where k represents the current integer.
Program to print the given triangle number pattern
/** * C program to print the given number pattern */ #include <stdio.h> int main() { int i, j, k, N; printf("Enter N: "); scanf("%d", &N); // k represents the current integer k = 1; for(i=1; i<=N; i++) { for(j=1; j<=i; j++) { // Print 1 if current integer k is odd if(k % 2 == 1) { printf("1"); } else { printf("0"); } k++; } printf("\n"); } return 0; }
Output
Enter N: 5
1
01
010
1010
10101
1
01
010
1010
10101
You can also print the given number pattern without using if else. Below is a simple but tricky program to print the same number pattern. It uses bitwise operator to check even odd.
/** * C program to print the given number pattern */ #include <stdio.h> int main() { int i, j, k, N; printf("Enter N: "); scanf("%d", &N); // k represents the current integer k = 1; for(i=1; i<=N; i++) { for(j=1; j<=i; j++) { printf("%d", (k & 1)); k++; } printf("\n"); } return 0; }
Screenshot
NOTE: You can also obtain the reverse of the given pattern
You just need to swap the two printf() statements. Means just replace the printf("1"); with printf("0");.
Happy coding ;)