In this tutorial, you will learn how to write a C++ Program to print patterns using looping statements.

C++ Programs – Pattern Printing

1. Pattern – Right Triangle

In this example, we will write a C++ program to print the following start pattern to console. We shall read the number of rows from user and print start pattern.

Pattern

For an input number of 4, following would be the pattern.

*
* *
* * *
* * * *

main.cpp

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter first number  : ";
    cin >> n;
    
    int i = 1;
    while (i <= n) {
        int j = 1;
        while (j <= i) {
            cout << "* ";
            j++;
        }
        cout << endl;
        i++;
    }
}

Inner while loop prints a single row. Outer while loop helps to print n number of rows.

In other words, outer while loop prints the rows, while inner while loop prints columns in each row.

Output

Enter first number  : 5
* 
* * 
* * * 
* * * * 
* * * * * 
Program ended with exit code: 0
Enter first number  : 7
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
Program ended with exit code: 0
ADVERTISEMENT

2. Pattern – Inverted Right Triangle

In this example, we will write a C++ program to print the following start pattern to console.

Pattern

For an input number of 4, following would be the pattern.

* * * *
* * *
* *
*

main.cpp

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter first number  : ";
    cin >> n;
    
    int i = 1;
    while (i <= n) {
        int j = n;
        while (j >= i) {
            cout << "* ";
            j--;
        }
        cout << endl;
        i++;
    }
}

Output

Enter first number  : 5
* * * * * 
* * * * 
* * * 
* * 
* 
Program ended with exit code: 0
Enter first number  : 8
* * * * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 
Program ended with exit code: 0

3. Pattern – Number Triangle

In this program, we will print a number triangle.

Pattern

For an input number of 5, following would be the pattern.

1
  2   3
  4   5   6
  7   8   9  10
 11  12  13  14  15

main.cpp

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter first number  : ";
    cin >> n;
    
    int i = 1, k = 1;
    while (i <= n) {
        int j = 1;
        while (j <= i) {
            cout << k << "\t";
            j++;
            k++;
        }
        cout << endl;
        i++;
    }
}

Output

Enter first number  : 4
1	
2	3	
4	5	6	
7	8	9	10	
Program ended with exit code: 0
Enter first number  : 8
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	26	27	28	
29	30	31	32	33	34	35	36	
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned to write C++ Programs to print different types of patterns.