C++: Printing a Bordered Asterisk Triangle


A modification to our code for the filled asterisk triangle can produce an output like the one given below. As you can see, only the border of the triangle is being printed with the asterisks and the inner area is blank. Well, blank means white-spaces to cover up the gap.

Simply, we can use the same source code we used for printing an Asterisk triangle. The only modification is the introduction of conditions inside the loop that prints the triangle. First of all, we need to print asterisks throughout for the last row as the last one makes up one side of the triangle. Hence, when i=n, the program should print asterisks throughout. For the rest of the cases, we need to print asterisk only at the starting and the ending of each row. Other than that, it should be white-spaces. Again, note that we need two white-spaces to maintain the alignment of the triangle.

Source Code


#include<iostream>
#include<stdlib.h>
#include"conio.h"
using namespace std;
void main()
{
 system("cls");
 int n,i,j;
 cout<<"\nEnter the number of stars: ";
 cin>>n;
 for(i=0;i<n;i++)
 {
  cout<<"\n";
  for(j=0;j<n-i;j++) //Indentation Loop
   cout<<" ";
  for(j=0;j<=i;j++) //Design Loop
  {
   if(i==n-1) //To print asterisks throughout for the last row
    cout<<"* ";
   else if((j==0)||(j==i)) //In all other cases, print asterisks at the starting and ending of a row
    cout<<"* ";
   else //Fill the inner part with spaces. Two spaces are required.
    cout<<"  ";
  }
 }
 getch();
}

Analysis


There is no need for further explanation. We've only added some conditions to the Design Loop to implement the functionality of the filling of the triangle. Except one case, the conditions are to fill the triangle with white-spaces unless j=0 [Starting] or j=i [Ending] where we fill asterisk. Thus, you get a bordered triangle from top to bottom. But if we are to give just two conditions, the last row would also be filled with white-spaces except for the first and last part. Hence, we need to exclude the last row from these conditions as the last row needs to be filled with asterisks only. Hence, the primary if condition is to check whether last row has been reached and if true, fill it with asterisks only. i.e, when i=n-1 as we are beginning from i=0.

I'm sure this was an easy task. Again, I'll give yet another task. Try to get an inverted triangle as the output. You can try for both filled and bordered versions of the two asterisk triangles. Just reverse the whole logic and you'll indeed get the answer.

Advertisements