Triangle code

Mar 25, 2017 at 1:58am
I just finished this bit of code and wanted to see if there's any way I can improve it. I am trying to learn new, more efficient techniques to code so any criticism would be extremely helpful...Oh! and the point of this program is to make a triangle with x amount of lines
Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 #include <iostream>

int main() {
    int lines=0;
    std::cout<<"Enter the height of the triangle\n";
    std::cin>>lines;
    for(int c=0; c<lines;c++)
    {
        int space;
        space=lines;
        space-=c;
     std::cout << std::string( space, ' ' )<<std::string( c*2, '*')<<'*'<<"\n";
    }
    return 0;
}
Last edited on Mar 25, 2017 at 2:00am
Mar 25, 2017 at 7:08am
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;

int main()
{
   int lines = 0;
   cout << "Enter the height of the triangle: ";
   cin >> lines;

   for ( int c = 1; c <= lines; c++ )  cout << string( lines - c, ' ' ) + string( 2 * c - 1, '*' ) + '\n';
}


or

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;

int main()
{
   int lines = 0;
   cout << "Enter the height of the triangle: ";
   cin >> lines;

   for ( int c = 1, space = lines - 1; space >= 0; c += 2, space-- )  cout << string( space, ' ' ) + string( c, '*' ) + '\n';
}


or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
   int lines = 0;
   cout << "Enter the height of the triangle: ";
   cin >> lines;

   for ( int i = 1; i <= lines; i++ )
   {
       for ( int j = 1;  j < lines + i; j++ ) cout << ( i + j <= lines ? ' ' : '*' );
       cout << '\n';
   }
}



or

Run from the command line by, e.g.,
triangle.exe 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cstdlib>
using namespace std;

int main( int argc, char *argv[] )
{
   int lines = atoi( argv[1] );

   for ( int i = 1; i <= lines; i++ )
   {
       int j = 0;
       while ( ++j <= lines - i ) cout << ' ';
       while ( ++j <= lines + i ) cout << '*';
       cout << '\n';
   }
}


    *
   ***
  *****
 *******
*********
Last edited on Mar 25, 2017 at 9:08am
Topic archived. No new replies allowed.