Write a c program to print triangle pattern of numbers and stars (*). In this tutorial, we are going to write a c code to print triangle pattern of numbers , stars (*) . This type of pattern questions in c asked in interviews and in exams.
C Program to Print Triangle Pattern of 0 and 1
In this first example, We are going to write a c program which prints a triangle pattern of 0 and 1.
1 2 3 4 5 6 7 8 9 |
1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <stdio.h> int main(){ int i, j,temp = 1; for (i = 1; i<= 5; i++) { printf("\n"); for (j = 1; j <= i; j++){ printf("%d", temp % 2); temp++; } if (i % 2 == 0) temp = 1; else temp = 0; } return(0); } |
In this second example, we write a c program to print triangle pattern of number 1 to 5.
1 2 3 4 5 |
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <stdio.h> int main() { int i,j; for(i=1;i<=5;++i) { for(j=1;j<=i;++j) { printf("%d ",j); } printf("\n"); } return 0; } |
C Program to Print Triangle of Numbers in Reverse Order
1 2 3 4 5 |
5 4 3 2 1 4 3 2 1 3 2 1 2 1 1 |
To print the triangle pattern in reverse order. Initialize i with input number. So in my case it’s 5. Then after printing every row start decrementing it.
1. In first for loop, initialize i with 5. Check the condition i is greater than or equal to 1. And after every iteration we start decrementing it’s value.
1 2 |
for(i=5;i>=1;i--){ } |
2. In second loop, j is initialized with the value of i.
1 2 3 |
for(j=i; j>=1; j--){ printf("%d ",j); } |
So let’s the value initialized is 5. 5 is greater than or equal to 1. So it prints
5 4 3 2 1
Now the condition goes false after 1 so it’s terminate. Similarly it goes for next iteration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <stdio.h> int main() { int i,j; for(i=5;i>=1;i--) { for(j=i;j>=1;j--){ printf("%d ",j); } printf("\n"); } return 0; } |
C Program to Print Triangle Pattern of Stars (*)
1 2 3 4 5 |
* * * * * * * * * * * * * * * |
Write a program to print triangle pattern using star(*) is mostly asked an interviews when you are fresh out of college. Let’s write a c code to print triangle pattern of stars.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> int main() { int i,j; for(i=1;i<=5;++i) { for(j=1;j<=i;++j) { printf("* "); } printf("\n"); } return 0; } |
C Program to Print triangle pattern of Stars (*) in Reverse Order
1 2 3 4 5 |
* * * * * * * * * * * * * * * |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> int main() { int i,j; for(i=5;i>=1;i--){ for(j=i;j>=1;j--){ printf("* "); } printf("\n"); } return 0; } |