Hi,
I need to draw a right triangle, based on the height and the base of it. An Isosceles one is easy to draw, but a randomly chosen relation between the height and the base (which gives me a right triangle other than 90, 45, 45) needs to be based on a mathematical proximity, and that I find harder to implement.
Thanks in advance, Yael.

an example of 5 over 8 right triangle, doesn't have to be exactly this way, but has to look good

good one:
*
***
*****
*******
********

bad one:
*
**
***
****
********

Recommended Answers

All 13 Replies

Post code because its a bit hard for us to see the program you wrote on your monitor.

uhmmm try this one...

input a number first then press enter:

#include<iostream.h>
   int main()
{ 
    
    
     int num, row;
     cin>>num;
     for(row=0;row<num;row++)
     {
        for (int a=0; a<=row;a++)
        {
            cout<<"*";
            }
            for (int b=num;b>row+1;b--)
            cout<<" ";
            cout<<endl;
            }
            cin.ignore();
            cin.ignore();
            return 0;
            }
#include <cstdlib>
#include <iostream>

using namespace std;

#define INPUT(a) cin >> a
#define PRINTLN(a) cout << a << endl
#define PRINT(a) cout << a << flush

class Triangle
{
      private:
             int *height, *base;
             
      public:
             Triangle(){PRINTLN("Enter the height"); height = new int; INPUT(*height); PRINTLN("Enter the base"); base = new int; INPUT(*base);};
             Triangle(int &h, int &b){height = new int(h); base = new int(b);};
             ~Triangle(){delete height; delete base;};
             void display();
             double area(){return (.5 * (*height) * (*base));};
};

void Triangle::display()
{
     
  if((*height) < (*base))
  {
      for(int i = 0; i <= (*height); i++)
      {          
           for(int x = 0; x < (static_cast<double>(*base)/(*height)) * i; x++)
                 PRINT("*");
                 
           PRINTLN("");
      }
  }
  else
  {
      for(int i = 0; i <= (*base); i++)
      {          
           for(int x = 0; x < (static_cast<double>(*height)/(*base)) * i; x++)
                 PRINT("*");
                 
           PRINTLN("");
      }
  }   
     
};

int main(int argc, char *argv[])
{    
    Triangle *t = new Triangle();
    
    t->display();
    PRINTLN(t->area());
    
    t->Triangle::~Triangle();
    delete t;

    system("PAUSE");
    return EXIT_SUCCESS;
}

--Basically I used the Whiever-is-greater / whichever-is-lower ratio method to determine the shape of the triangle.

Hopefully this helps XP

Thanks everyone! Alex, I used your logic and it works! I had something in mind, but this one was even better!
:icon_cheesygrin:

No problem, but I don't believe I really posted a solution.

You'll have to do some kind of comparison to ensure that the starting amount of the triangle, and the ending (the "tips") are recognizable when entering parameters for the triangle.

Either that or use a cstring object/function that performs visual spacing so that the triangle looks more like a triangle.

Another suggestion would be to add a starting case and ending case for the triangle, so that when you begin creating the triangle (and finish), tips are ensured to show.

By using my program if you enter something like 2 for height and 9 for base you'll get a funky looking triangle. I doubt that's something you want to suffice with.

Instead have the first and last call be something like (first line must have at most (1/5)base amount of stars.

Hi Alex,
I needed the math calc line, for the condition of the for loop, the rest was already there (it's part of a project, with moving shapes on board, and most on the code I already finished...) - the only problem I'm facing now is that from some reason the last line of the right triangle (the base)- and only the right triangle (meaning, I don't have this problem with the rectangle, the square or the Isosceles right triangle) is not recognized and get swallowed by the bounds of the board:

-----------------------------------------
-----------------------------------------
-----------------------------------------
-------------------*---------------------
-------------------**-------------------
-------------------***------------------
-----------------------------------------


-----------------------------------------
-----------------------------------------
-----------------------------------------
-----------------------------------------
-----------------------------------------
-------------------*---------------------
-------------------**-------------------

this is an example of what it looks like when I move it 2 lines downward, instead of stopping when it sees the board's bound at the bottom.
this is the piece of the code, it's part of a big project...

void MovingRightTriangle :: UpdateBoard(char charact){
	Shape::the_board.area[shape_location.y+1][shape_location.x] = charact;
	for (int j=2 ; j <= (Yaxis_length) ; j++){
		for (int i=0 ; i < (static_cast<double>(Xaxis_length)/(Yaxis_length))*j; i++){
			Shape::the_board.area[j+shape_location.y][i+shape_location.x] = charact;	
		}
	}
}

the location of the shape on the board: shape_location.x, shape_location.y (it's the x, y)
the height = Yaxis_length
the base = Xaxis_length
the board is a static member of base class Shape
the first line of the function enforces the peak to have just one character
I hope that someone will understand this code, detached from the rest of the code...

Hi Alex,
It's working! I changed some lines which made all the troubles and now it looks like this:

void MovingRightTriangle :: UpdateBoard(char charact){
	for (int j=0 ; j < Yaxis_length ; j++){
		for (int i=0 ; i < (static_cast<double>(Xaxis_length)/(Yaxis_length))*(j+1); i++){
			Shape::the_board.area[j+shape_location.y][i+shape_location.x] = charact;	
		}
	}
}

BTW, for the rectangle it looks like this :

void MovingRectangle :: UpdateBoard(char charact){
	for (int j=shape_location.y ; j < (shape_location.y + Yaxis_length) ; j++){
		for (int i=shape_location.x ; i < (shape_location.x + Xaxis_length) ; i++){
			Shape::the_board.area[j][i] = charact;	
		}
	}
}

now I don't have the problem with the lower bound any more
:-)
thanks!

I need a few answers before I can help you further.

First, how is the object moving? User input with keyboard (like pressing the right arrow key will make the object shift to the right, etc)?

If this is the case what I'd do is "catch" the users input (such as, the key they used) and figure out how this effects the values of your object.

For example, if the boards dimensions are 7x9 (7 rows down, 9 columns over) then it would look like this

---------
---------
---------
---------
---------
---------
---------

and an object within it can "visually" move around when I use a key command. If I press the right button then the column property of the object is incremented and the board is normally updated with dashes but includes the update for the object itself.

Since you know the dimensions of your object, you can probably treat it like a boxed-object (an object that exists in some kind of invisible bordering) and restrict movement if--

->the objects current position on the screen, plus its height (or length) does not exceed the board.

i.e...

---------
---------
---------
-----*---
-----**--
-----***-
---------

this triangle can move one more time to the right. It's position is (according to your syntax) Shape::the_board.area[y][x] where [y][x] is the dash right above the first asterisk. This has no character value but symbolically represents the starting position of your triangle.

If this is the case then simply save a copy of the old y and x positions and compare it to the new y and x positions. You can do something like oldx and oldy to store the values of the objects location before the move.

Then do subtraction - obviously if the x - oldx is positive you're planning on moving to the right. If this pushes the object out of bounds you dont want this to happen.

Assuming you have access to the value controlled by the user's input...

->create a variable that stores the objects position (oldx for the previous x position and oldy for the previous y position)
->perform bounds checking - it will most likely be ok for you to treat your triangle like a square (i.e. if your triangle is 3h 3b you can treat it like a 3x3 square during bounds checks).
->obviously use the value of the difference of the variables (x with oldx and y with oldy) to determine the new direction of the object. If it will cross the bound on a new move you only need to negate that movement from occurring and setting the newly placed values back to the old ones (because if the move fails then you need to make sure the variables are updated to the objects true position).

I'd need more information of the class you're using, knowledge of whether you have direct access to modify this class (or not) or any other useful information.

Edit: Whoops looks like you figured it out. Good deal =P

Hi Alex,
thanks for replying, I'm new to this website, and to all of this, actually... but I just thought that you might be interesting on understanding the properties of the shapes:
the location on board, the length and width or height and base of the shape, the vertical and horizontal movements (movement vector)- all determined randomly when a shape is being constructed. Making a move means that the shape has to move on both axises according to its movement vector, inside the bounds of the board- if a collision happens to occur, the shape will stop at the bound of the board and will not complete a "full" step, next time, it will move to the other direction.
that's more or less the whole story.
Thanks!
Yael

I figured as much.

This project reminds me of the game "doodlebugs" except I had to perform that code in Java.

Hi,
I need to draw a right triangle, based on the height and the base of it. An Isosceles one is easy to draw, but a randomly chosen relation between the height and the base (which gives me a right triangle other than 90, 45, 45) needs to be based on a mathematical proximity, and that I find harder to implement.
Thanks in advance, Yael.

an example of 5 over 8 right triangle, doesn't have to be exactly this way, but has to look good

good one:
*
***
*****
*******
********

bad one:
*
**
***
****
********

can u plz send me program about Drawing Right Triangle about C++ problem..........u guys have exact copy but i need help how u guys did
so send me in <EMAIL SNIPPED>
thnx u so much
i m waiting 4 ur reply back in my yahoo mailll

hi! pls check my problem about a Right Triangle...

this is my problem about my program on how to make a right triangle using loop in c++.
word problem:
create a program that displays the following right triangles. the user must be the one to specify the height(number of rows) of the triangle. the user must be able to repeat the process if he/she wants to.

sample display with a height of five(5):
55555
4444
333
22
1

ok! this is the output.. thank you! ^_^

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.