
- Learn C By Examples Time
- Learn C by Examples - Home
- C Examples - Simple Programs
- C Examples - Loops/Iterations
- C Examples - Patterns
- C Examples - Arrays
- C Examples - Strings
- C Examples - Mathematics
- C Examples - Linked List
- C Programming Useful Resources
- Learn C By Examples - Quick Guide
- Learn C By Examples - Resources
- Learn C By Examples - Discussion
Triangle Printing In C
This section will deal to enhance understanding of loops and nested loops. We shall print various pattern to learn how loops in C works.
Equilateral Triangle
#include <stdio.h> int main() { int n,i,j; printf("Enter number of rows: "); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=n-i;j++) printf(" "); for(j=1;j<=i;j++) printf("* "); printf("\n"); } return 1; }
The output should look like this −
* * * * * * * * * * * * * * * * * * * * *
Upside Down Triangle
This program will print a triangle in upside down
#include <stdio.h> int main() { int n,i,j; n = 5; for(i=1;i<=n;i++) { for(j=1;j<=n-i;j++) printf(" "); for(j=1;j<=i;j++) printf("* "); printf("\n"); } return 1; }
The output should look like this −
* * * * * * * * * * * * * * *
Right Triangle
#include <stdio.h> int main() { int n,i,j; n = 5; for(i=1;i<=n;i++) { for(j=1;j<=i;j++) printf("*"); printf("\n"); } return 0; }
The output should look like this −
* * * * * * * * * * * * * * *
Top-Down Right Triangle
#include <stdio.h> int main() { int n,i,j; n = 5; for(i=n;i>=1;i--) { for(j=1;j<=i;j++) printf("*"); printf("\n"); } return 0; }
The output should look like this −
* * * * * * * * * * * * * * *
Top-Down Right Triangle - 2
#include <stdio.h> int main() { int n,i,j; n = 5; for(i = 0; i < n; i++) { for(j=0; j<i; j++) { printf(" "); } for(j=i; j < n; j++) { printf(" *"); } printf("\n"); } return 0; }
The output should look like this −
* * * * * * * * * * * * * * *
Floyd's Triangle
#include <stdio.h> int main() { int n,i,j,k=1; n = 5; for(i = 1; i<=n;i++) { for(j=1;j< =i;j++) printf("%3d",k++); printf("\n"); } return 0; }
The output should look like this −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Pascal's Triangle
#include <stdio.h> int factorial(int n) { int f; for(f=1;n>1;n--) f*=n; return f; } int ncr(int n,int r) { return factorial(n)/(factorial(n-r)*factorial(r)); } int main() { int n,i,j; n = 5; for(i=0;i<=n;i++) { for(j=0;j<=n-i;j++) printf(" "); for(j=0;j<=i;j++) printf("%4d",ncr(i,j)); printf("\n"); } return 0; }
The output should look like this −
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
Advertisements