C++ Program to Print Left Triangle Star Pattern


Star patterns are interesting problems to display different shapes like right-angled triangles or other triangular and diamond shapes using asterisks ‘*’. These shapes are called star patterns. In this article, we will see how to display the left triangle start pattern in C++. Here we take the number of lines for the star pattern as input. It will print the pattern for that number of lines.

We will develop the logic to print stars in the following table. Let us follow the table for a better understanding −

*
* *
* * *
* * * *
* * * * *
* * * * * *

In this example, there are 6 lines. So consider n = 6. For each line ‘i' it will follow the star count

Line number (i) Star Count (j)
1 1
2 2
3 3
4 4
5 5
6 6

Here j follows i, when so at any line ‘i', it has ‘i' number of stars at that line. Let us see the algorithm for this −

Algorithm

  • read number of lines as input n
  • for i ranging from 1 to n, do
    • for j ranging from 1 to i, do
      • display asterisk ( * )
    • end for
    • move the cursor to the next line
  • end for

Example

#include <iostream>
#include <ctype.h>
using namespace std;
void solve( int n ){
   int i, j;
   for( i = 1; i <= n; i++ ) {
      for( j = 1; j <= i; j++ ) {
         cout << "* ";
      }
      cout << endl;
   }
}
int main(){
   int n = 10;
   cout << "Left Star Pattern using " << n << " number of lines:" << endl;
   solve( n );
}

Output

Left Star Pattern using 10 number of lines:
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * * 
* * * * * * * * * * 

Output (for n = 18)

Left Star Pattern using 18 number of lines:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *

Conclusion

Displaying star patterns helps to understand nested loops while learning programming in any language. In this article, we have seen how to display the left triangle using asterisks (stars) where the number of lines is given as input. It will display the number of lines where each line has that much number of stars in it. We have also discussed a tabular method to formulate the number of stars for the ith line. Using this idea we can simply change the formula to display other types of patterns as well.

Updated on: 13-Dec-2022

896 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements