answersLogoWhite

0

#include<iostream>

#include<vector>

class triangular_matrix_t

{

private:

std::vector < std::vector<unsigned> > m_matrix;

unsigned m_gradiant;

public:

triangular_matrix_t (unsigned rows, unsigned initial_length = 1,

unsigned gradiant = 1): m_matrix (rows), m_gradiant (gradiant)

{

unsigned row_length = initial_length;

for (unsigned row=0; row<rows; ++row)

{

m_matrix[row].resize (row_length);

row_length += m_gradiant;

}

}

void set (unsigned row, unsigned column, unsigned value)

{

if (row<m_matrix.size())

{

if (column<m_matrix[row].size())

{

m_matrix[row].at(column) = value;

}

}

}

unsigned at(unsigned row, unsigned column)

{

if (row<m_matrix.size() && column<m_matrix[row].size())

return(m_matrix[row].at(column));

return 0;

}

unsigned get_height() const {

return(m_matrix.size()); }

unsigned get_length(const unsigned row) const {

return row<m_matrix.size() ? m_matrix[row].size() : 0; }

unsigned get_gradiant() const {

return m_gradiant; }

};

std::ostream& operator<< (std::ostream& os, triangular_matrix_t& matrix)

{

for (unsigned row=0; row<matrix.get_height(); ++row)

{

for (unsigned col=0; col<matrix.get_length(row); ++col)

{

os << matrix.at(row, col) <<'\t';

}

os << std::endl;

}

return os;

}

int main()

{

triangular_matrix_t matrix (10);

for (unsigned row=0; row<matrix.get_height(); ++row)

{

for (unsigned col=0; col<matrix.get_length(row); ++col)

{

matrix.set (row, col, (row+1)*(col+1));

}

}

std::cout << "Triangular matrix with 10 rows:\n" << std::endl;

std::cout << matrix << std::endl;

}

Output:

Triangular matrix with 10 rows:

1

2 4

3 6 9

4 8 12 16

5 10 15 20 25

6 12 18 24 30 36

7 14 21 28 35 42 49

8 16 24 32 40 48 56 64

9 18 27 36 45 54 63 72 81

10 20 30 40 50 60 70 80 90 100

User Avatar

Wiki User

10y ago

Still curious? Ask our experts.

Chat with our AI personalities

ViviVivi
Your ride-or-die bestie who's seen you through every high and low.
Chat with Vivi
LaoLao
The path is yours to walk; I am only here to hold up a mirror.
Chat with Lao
BlakeBlake
As your older brother, I've been where you are—maybe not exactly, but close enough.
Chat with Blake

Add your answer:

Earn +20 pts
Q: Code for triangular matrix using c plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp