Upright Hollow Triangle with given base size – Computer Sir Ki Class


Code Learning #CPP#3111 siteicon   siteicon   siteicon  

Upright Hollow Triangle with given base size

Printing upright hollow triangle with given base size.

Learning Objectives

  • Learn the logic of leaving spaces before printing a character and then after the character for internal spaces while printing patterns.


Source Code

TC++ #3111

int main()
int n=5;
int i,j,k=0;
int sp;
int g=n;
for (i=1; i {
for (sp=g; sp>=0; sp--) cout << " ";
for (j=1; j {
if(j==1 || j==(k-1) || i==(n+2)) cout << "*";
else cout << " ";
cout << endl;
return 0;

Source Code


Test it !
  Related (?) :

Run Output

* *
* *
* *
* *

Code Understanding

int n=5; //This is given base size unit n when actual base would be 2*n+1;
int i,j,k=0; //Initialised for loop counting
int sp;  //Used for space counting
int g=n;  //Used for gap initialisation
for (i=1; i<n+3; i++)  //outer loop for row counting.
for (sp=g; sp>=0; sp–) cout << ” “;  //For space before the first * in a row
for (j=1; j<k; j++)                //This loop prints the row elements
if(j==1 || j==(k-1) || i==(n+2)) cout << “*”;
character * is printed in specific conditions as given
else cout << ” “; //These are spaces inside the triangle.
cout << endl;         //This helps to move to next row.
k+=2;                     //This adjusting k for next row of *
g–;                         //This adjusting initial gap for printing the next row

Common Errors

  • This code is definitely highly error prone. Students are advised to experiment with different loop settings to get every thing correctly.

Suggested Filename(s): upholtri.cpp


sunmitra| Created: 28-Jan-2018 | Updated: 28-Jan-2018|