user3015519
user3015519

Reputation: 23

I'd Like to know how to make an asterisk right triangle(S) in C++ using a loop

I want something like this:

****      ****
***        ***
**          **
*            *

I tried this:

void roadBound() {

    for( int i = 1; i <= 10; i++ ){
        for( int j = 0; j < i; j++ ){
           cout << "*" ;
        }
        cout << endl;
    }
}

But it wasnt even close. Please help

Upvotes: 0

Views: 2834

Answers (4)

BLUEPIXY
BLUEPIXY

Reputation: 40145

void roadBound(int n) {
    const int gap = 6;
    string str = string(n, '*') + string(gap, ' ') + string(n, '*');
    int f=n,b=n+gap-1;
    while(n--){
        str[f--]=str[b++]=' ';
        cout << str << endl;
    }
}

Upvotes: 0

Chara
Chara

Reputation: 338

So far, your code produces this:

*
**
***
****
*****
******
*******
********
*********
**********

Which looks like a pretty good right triangle, so I think you're on the right track. To make the image you had above, you'll need to throw in some spaces, and make sure that every line is the same length. If it's okay, I think what you're asking is way easier with only one loop. Try this:

#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;

int main() {
int height = 4;
int line = height * 4;
for( int i = height; i > 0; --i ){
        string stars (i, '*');
        int space = line - (i * 2);
        string spaces (space, ' ');
        cout << stars << spaces << stars << endl;
    }
}

This code produces:

****        ****
***          ***
**            **
*              *

which seems to have a few more spaces than your example up there, but you can fix that by adding a variable before the loop for the maximum length of space you want, and then decrementing it by two each time through the loop.

Upvotes: 1

masoud
masoud

Reputation: 56479

This uses 3 loops inside another loop

const int ROW = 4;
const int GAP = 7;

for (int i=ROW, g=GAP; i>=0; i--, g+=2)
{
    for (int j=0; j<i; j++) cout << '*';
    for (int j=0; j<g; j++) cout << ' ';
    for (int j=0; j<i; j++) cout << '*';
    cout << '\n';
}

Output

****      ****
***        ***
**          **
*            *

Live code

Upvotes: 0

Abu Yousuf
Abu Yousuf

Reputation: 6107

You can try this

int lf=4,md=4, N=4;
for( int i = 1; i<=N; i++ )
{
   for( int j =1; j<=lf; j++ )
      cout<<"*";
    for( int j =1; j<=md; j++ )
      cout<<" ";
    for( int j =1; j<=lf; j++ )
      cout<<"*";
    cout<<"\n";
       lf--;
      md+=2;
}

Upvotes: 0

Related Questions