print star triangle in c++ code example

Example 1: print pattern and space in cpp

//WAP to print triangle pattern... LOGIC
int num{}, i{1};
  cin >> num;
  while (i <= num) {
    for (int space = 1; space <= (num - i); space++) {  // space
      cout << " ";
    }
    for (int value = 1; value <= (2 * i - 1); value++) {  // value
      cout << value;
    }
    cout << endl; //next row
    i++;
  }

Example 2: nested for loops pyramid c++

//C++ program to display hollow star pyramid

#include<iostream>
using namespace std;

int main()
{
   int rows, i, j, space;

   cout << "Enter number of rows: ";
   cin >> rows;

   for(i = 1; i <= rows; i++)
   {
      //for loop to put space in pyramid
      for (space = i; space < rows; space++)
         cout << " ";

      //for loop to print star
      for(j = 1; j <= (2 * rows - 1); j++)
      {
         if(i == rows || j == 1 || j == 2*i - 1)
            cout << "*";
         else
            cout << " ";
      }
      cout << "\n";
   }
   return 0;
}

Tags:

Cpp Example