This program draws right triangles : Inserter « Overload « C++






This program draws right triangles

This program draws right triangles

#include <iostream>
using namespace std;

class triangle {
  int height, base;
public:
  triangle(int h, int b) { height = h; base = b; }
  friend ostream &operator<<(ostream &stream, triangle ob);
};

// Draw a triangle.
ostream &operator<<(ostream &stream, triangle ob)
{
  int i, j, h, k;

  i = j = ob.base-1;
  for(h=ob.height-1; h; h--) {
    for(k=i; k; k--) 
      stream << ' ';
    stream << '*';
    
    if(j!=i) {
      for(k=j-i-1; k; k--)
        stream << ' ';
      stream << '*';
    }

    i--;
    stream << '\n';
  }
  for(k=0; k<ob.base; k++) stream << '*';
  stream << '\n';

  return stream;
}

int main()
{
  triangle t1(5, 5), t2(10, 10), t3(12, 12);

  cout << t1;
  cout << endl << t2 << endl << t3;

  return 0;
}
           
       








Related examples in the same category

1.Create a non-friend inserter.Create a non-friend inserter.
2.Use a friend inserter for objects of type MyClass.Use a friend inserter for objects of type MyClass.
3.PhoneNumber inserter functionPhoneNumber inserter function
4.An inserter can be used to output data in any formAn inserter can be used to output data in any form
5.Use friend function to operator: <<, >>Use friend function to operator: <<, >>
6.Output account info to a file using an inserter.Output account info to a file using an inserter.