Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing triangle without nested conditionals

Tags:

c++

loops

#include<iostream>

using namespace std;
int main() {
    int height, star{ 0 };
    cout << "Enter height of triangle";
    cin >> height;
    for(int i=1; i<=height; i++)
    {
        if(star<i)
        {
            cout << "*";
            ++star;
            continue;
        }
        cout << endl;
        star = 0;
    }
}

This is printing stars in a line I want to print one star in 1st line then 2 in second line and so forth.

Example:

*
**
***
****

Image:

enter image description here

like image 516
Mohiuddin Ahmed Avatar asked Dec 03 '20 21:12

Mohiuddin Ahmed


1 Answers

You should be able to simply do this:

#include <iostream>

using namespace std;

int main()
{
    int height;
    cout << "Enter height of triangle";
    cin >> height;
    for(int i=1; i<=height; i++)
    {
        cout << string(i, '*') << endl;            
    }
}
like image 152
Icemanind Avatar answered Oct 05 '22 16:10

Icemanind