Post

pattern printing in c

pattern printing in C

pattern printing in c

Let’s do a quick crash revision on pattern printing in C. These are the classics interviewers love to throw at firmware/C devs.


1. Right-Angle Triangle

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main() {
    int n = 5;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=i;j++){
            printf("* ");
        }
        printf("\n");
    }
}

Output:

1
2
3
4
5
* 
* * 
* * * 
* * * * 
* * * * * 

2. Inverted Triangle

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main() {
    int n = 5;
    for(int i=n;i>=1;i--){
        for(int j=1;j<=i;j++){
            printf("* ");
        }
        printf("\n");
    }
}

Output:

1
2
3
4
5
* * * * * 
* * * * 
* * * 
* * 
* 

3. Pyramid

1
2
3
4
5
6
7
8
9
#include <stdio.h>
int main() {
    int n=5;
    for(int i=1;i<=n;i++){
        for(int s=1;s<=n-i;s++) printf(" ");  // spaces
        for(int j=1;j<=2*i-1;j++) printf("*");
        printf("\n");
    }
}

Output:

1
2
3
4
5
    *    
   ***   
  *****  
 ******* 
*********

4. Diamond

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
int main() {
    int n=5;
    // upper half
    for(int i=1;i<=n;i++){
        for(int s=1;s<=n-i;s++) printf(" ");
        for(int j=1;j<=2*i-1;j++) printf("*");
        printf("\n");
    }
    // lower half
    for(int i=n-1;i>=1;i--){
        for(int s=1;s<=n-i;s++) printf(" ");
        for(int j=1;j<=2*i-1;j++) printf("*");
        printf("\n");
    }
}

Output:

1
2
3
4
5
6
7
8
9
    *    
   ***   
  *****  
 ******* 
*********
 ******* 
  *****  
   ***   
    *    

5. Numbers Triangle

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main() {
    int n=5;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=i;j++){
            printf("%d ", j);
        }
        printf("\n");
    }
}

Output:

1
2
3
4
5
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

Key takeaways for revision:

  • Outer loop → rows (lines).
  • Inner loop(s) → spaces & symbols/numbers.
  • Think in terms of:

    1. Spaces before the symbol
    2. Printing the symbol (or number)

This post is licensed under CC BY 4.0 by the author.