Downward Hollow Triangle with given base size and left offset – Computer Sir Ki Class
  

Login
[lwa]



Code Learning #CPP#3116 siteicon   siteicon   siteicon  

Downward Hollow Triangle with given base size and left offset

Printing downward hollow triangle with given base size and left offset.

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++ #3116

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

Source Code

 

Test it !
  Related (?) :

Run Output

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

Code Understanding

int n=5;  //Number of base units where actual base size would be 2*n+1
int i,j,k=n*2+1;
i,j,k are loop indexes. k=n*2+1 as the first row will be the base in downward triangle
int sp; //For space counting before the printing of first * in a given row
int g=2; //Initial gap or left offset of the whole downward triangle.
for (i=1; i<n+3; i++) //Outer loop to print rows
{
for (sp=1; sp<=g; sp++) cout << ” “; //Loop to print initial spaces before first character
for (j=k; j>=1; j–)  //Internal loop to print each row element
{
if(j==k || j==1 || i==1) cout << ‘*’;
This condition is to print * only when given condition is met.
else cout << ‘ ‘;
This space would be internal spaces within the triangle
}
cout << endl; //new line after each row is printed
k-=2; //Preparing internal loop count for next iteration
g++;  //Preparing initial gap for next iteration
}

Notes

  • One can produce a filled triangle by filling a different character in the internal loop.

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): dnholtri.cpp



Share

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






Back