Start New Discussion within our Software Development Community

hi i am having trouble creating a series if triangles the number of triangles depsned on the users inout here is what i have so far any help would be great i ahve been at this for days. i know its the loop but i just cant see the problem.

#include <iostream> // using the main library
using namespace std;



// Function declarations

char this_char () ;
int get_num_tri () ;
void draw_tri ( char this_char, int num_tri ) ;

int main ()
{
	char this_char = '*' ;

    // Get number of triangles
	int num_tri ;
	num_tri = get_num_tri () ;


	// Draw triangles
	draw_tri ( this_char, num_tri ) ;

	return 0 ;

}

// Funtion to get user to input number of triangles.
int get_num_tri ()
{
	int num_tri ;
	cout << " Please enter the number of triangles you would like " << endl ;
	cin >> num_tri ;
	return num_tri ;
}



// Function to draw triangles.
void draw_tri (char this_char , int num_tri ) 
{
	for ( int i = 1 ; i <= num_tri ; i ++ )
	{// Nested loop.
		for ( int j = 1 ; j <= i ; j ++ )
       
		{
			cout << " * " ;
			
        }
		cout << endl << endl ;
		
	}
}

As written, your variable num_tri is controlling the size of the triangle, not the number of them.

To do what you intend to do, the outer loop of draw_tri() should control the number of triangles (based on num_tri), then you need a set of nested loops in there that does the drawing.

for( i = 0; i < num_tri; i++ )   //number of triangles
     for( j = 0; j < num_rows; j++ )   //control height of triangles
     {
          for( k = 0; k <= j; k++ )  //draw the rows
              cout << this_char << " ";   //use the character parameter you passed in!
          cout << endl;
      }

Val

This article has been dead for over six months. Start a new discussion instead.