78.8k views
3 votes
Write a program that asks the user to enter the size of a triangle (an integer from 1 to 50). Display the triangle by writing lines of asterisks. The first line will have one asterisk, the next two, and so on, with each line having one more asterisk than the previous line, up to the number entered by the user. On the next line write one fewer asterisk and continue by decreasing the number of asterisks by 1 for each successive line until only one asterisk is printed.

1 Answer

4 votes

Answer:

/*

* Program to print traingle using asterisk.

*/

#include<iostream>

using namespace std;

//Function to print n asterisk in a row.

void printAsterisk(int n)

{

for(int i = 0;i<n;i++)

cout<<"*";

}

int main()

{

//Variable to store size of trianle

int size;

cout<<"Enter the size of triangle"<<endl;

cin>>size;

//print asterik in increasing order line by line.

for(int i =0; i<size;i++)

{

printAsterisk(i);

cout<<endl;

}

//print asterik in decresing order line by line.

for(int i =size-1; i>0;i--)

{

printAsterisk(i-1);

cout<<endl;

}

}

Output:

Enter the size of triangle

10

*

**

***

****

*****

******

*******

********

*********

********

*******

******

*****

****

***

**

*

Explanation:

Since no programming language is mentioned therefore answer is provided in C++.

The above program will use two for loops to print the triangle using asterisk.

The first loop will print the asterisk line by line with each line having one more asterisk than the previous one till the size of the triangle.

The second for loop will print the asterisk using same logic as above but in reverse order.

Final output of triangle will be obtained.

User Sarath Rachuri
by
5.2k points