C++ Program to Print Upper Star Triangle Pattern


Asterisks "*" are used in star patterns to represent various shapes, such as right-angled triangles or other triangular and diamond shapes. Star patterns are the names for these forms. This tutorial will demonstrate how to use C++ to display the upper left triangle star pattern. Here, we accept as an input the number of lines in the star design. For that many lines, the pattern will be printed.

The following table will contain the logic we create to print stars. The following table can help us understand.

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

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 6
2 5
3 4
4 3
5 2
6 1

Here j follows the formula (n – i + 1), when so at any line ‘i', it has ‘(n – i + 1)' 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 (n – i + 1), 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 <= (n - i + 1); j++ ) {
         cout << "* ";
      }
      cout << endl;
   }
}
int main(){
   int n = 10;
   cout << "Upper left Star Pattern using " << n << " number of lines:" << endl;
   solve( n );
}

Output

Upper left Star Pattern using 10 number of lines:
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

Output (for n = 20)

Upper left Star Pattern using 20 number of lines:
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

Conclusion

In order to fully understand nested loops when studying programming in any language, star patterns are demonstrated. This article demonstrated how to use asterisks (stars) to display the upper left triangle when the number of lines is supplied. It will show how many lines there are with that many stars in each line. To calculate the number of stars for the ith line, a tabular approach has also been explored. Using this concept, we can easily modify the formula to show additional patterns.

Updated on: 13-Dec-2022

428 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements