How to Print Upside Down Filled Isosceles Triangle in C++


Isosceles triangle is a triangle that has two sides of equal length.

We are going to print this isosceles triangle in C++ program but we will print this triangle upside down(like in the output image).

Before jumping into code, If you look closer to image then you would come to know that there are five lines containing asterisks. There are 9 asterisks in first line and are decreasing by 2. Every next line is containing two asterisks down like 7,5,3 and 1.

Lets think what we need to code this isosceles triangle. We need a loop that will print character “*” as many times as needed. Loop should also be capable of tracking number of asterisks in a particular line. That can be done using a counter variable. Next we need one more loop that will point to next line. If there are 9 asterisks in first line then it will point the program to print 7 asterisks on next line and so on. If you look closer to image then you would also come to know there are empty spaces on the start of 2nd, 3rd, 4th and 5th line. To print these empty spaces, one more loop is required. So three loops and one counter variable makes this program to work.

Code To Print Upside Down Filled Isosceles Triangle in C++:

using namespace std;
int main()
    int counter=9;
    for(int line=1;line<=5;line++)
       for(int star=0;star<counter;star++)
       for(int c=0;c<line;c++)
     	     cout<<" ";  
    return 0;

Code Explanation:

The code given above prints upside down filled isosceles triangle in C++ language.

Recommended reading: C++ Program to add two numbers using classes

We declared a counter variable on the first line of main() function. This counter tells the loop how many asterisks to print in this loop iteration. For example, it is initialized as 9 and asks the loop to print 9 asterisks on first line. Then its value is decreased by 2 and it tells the loop to print seven asterisks on second line. There is one master loop that runs 5 times which represents the five lines of triangle. There are two nested loops, one prints asterisks on the screen while one prints empty spaces.


print isosceles triangle in C++

If you liked this article, then please consider sharing it with your friends and leaving a comment below.

You can also Click Here To Download Exercise Files.