Drawing a Triangle in Console window

0
1832

Here is a C++ code containing nested loops which is able of drawing a triangle in your console window.We can use loops easily to draw many structures in our console window, its not only drawing a triangle, we can make square, rectangle and circles etc . in this case We have to use the loops in nested form or simply one loop inside other.Lets look at the example:

[cpp]
// Nested ‘for’ loop drawing triangle in console window
#include <iostream>
using namespace std;
int main()
{
int height; // height of triangle
cout <<"Please enter height of your triangle:";
cin >> height; //triangle height

for (int i=1; i<=height;i++)
{
for (int j=1; j<=2*i-1;j++)
cout<<"*";
cout<<endl;
}
return 0;

}
[/cpp]

your output will look like this :

tri

For drawing a triangle in console first of all we defined a variable “height”, user entered the value of the height and then a “for loop” for height started, we nested a loop inside it in which the limit is ” 2*i-1 “,  these nested for loops adds two(*) to every next line as shown in the figure. Drawing a triangle in console window have no application but its just a practice to make a good style of your program.