Matrix33 in C++: Create, Add, Check & Program

  • C/C++
  • Thread starter mathmari
  • Start date
  • Tags
    C++
In summary, the code asks for a class named Matrix33 that has its dimensions fixed at 3x3. The class is created and memset is used to initialise it to 0. Next, the program asks for an input of 5 elements and each element is read and inserted into the matrix. Finally the matrix is returned.
  • #1
mathmari
Gold Member
MHB
5,049
7
Hey! :giggle:

I am looking the following exercise about C++.

(a) Create a class Matrix33 that describes a 2-dimensional $3\times3$ array of integers. At the construction of an element of the class allpositions of the array are initially zero (zero matrix). Implement methods to read and write values at the positions of tha array according to the line and column of each position.
(b) Implement a method IsDiagonal that checks if the array is diagonal.
(c) Support adding arrays by overloading the + operator. With data elements Matrix33 m1, m2; the array Matrix33 m3 = m1 + m2; will contain the sum of the arrays m1 and m2.
(d) Implement methods for reading array data from input and printing array data at output. Write a program that creates 2 elements of class Matrix33, reads their data from the input, adds them and prints the result of the addition to the output.
I searched online for some notes. Is the code as follows? :unsure:

Code:
#include <iostream>
#include <cstdlib>
using namespace std;

class Matrix
{
public:
    Matrix(); //Default constructor
    Matrix(int m, int n); //Main constructor
    void setVal(int m, int n); //Method to set the val of [i,j]th-entry

private:
    int m, n;
    int **p;
    void allocArray()
    {
        p = new int*[m];
        for(int i = 0; i < m; i++)
        {
            p[i] = new int[n];
        }
    }
};

Matrix::Matrix() : Matrix(1,1) {}
Matrix::Matrix(int m, int n)
{
    allocArray();
    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j < n; j++)
        {
            p[i][j] = 0;
        }
    }
}
 
Technology news on Phys.org
  • #2
Hey mathmari!

That works more or less.
However, the question asks for a class named Matrix33, which has its dimensions fixed to 3x3.
And the method setVal is missing a parameter to set the actual value, and it's also missing an implementation.
We're also missing a method to read a value in the matrix.
Furthermore, if we do new int[n](), then everything gets initialized to 0, so we don't have to do that explicitly then.
Or alternatively, we could just have an int a[3][3] as data member, although we need to memset it to 0 then. 🤔
 
  • #3
Klaas van Aarsen said:
Furthermore, if we do new int[n](), then everything gets initialized to 0, so we don't have to do that explicitly then.
Or alternatively, we could just have an int a[3][3] as data member, although we need to memset it to 0 then. 🤔

So for the part "Create a class Matrix33 that describes a 2-dimensional 3×3 array of integers. At the construction of an element of the class allpositions of the array are initially zero (zero matrix). " do we do the following?

Code:
#include <iostream>

class Matrix33 
{
int m[3][3];  
memset(m, 0, sizeof m); 
}
Or did you mean something else? :unsure:
 
  • #4
mathmari said:
So for the part "Create a class Matrix33 that describes a 2-dimensional 3×3 array of integers. At the construction of an element of the class allpositions of the array are initially zero (zero matrix). " do we do the following?
That wouldn't compile.
Instead it should be:
Code:
#include <cstring>

class Matrix33
{
public:
  Matrix33() {
    std::memset(m, 0, sizeof m);
  }
private:
  int m[3][3];
};
And actually, we can do:
Code:
class Matrix33
{
public:
  Matrix33() : m() {}
private:
  int m[3][3];
};
for the same effect. 🤔
 
  • #5
Klaas van Aarsen said:
That wouldn't compile.
Instead it should be:
Code:
#include <cstring>

class Matrix33
{
public:
  Matrix33() {
    std::memset(m, 0, sizeof m);
  }
private:
  int m[3][3];
};
And actually, we can do:
Code:
class Matrix33
{
public:
  Matrix33() : m() {}
private:
  int m[3][3];
};
for the same effect. 🤔

Ok!

So do we have at question (a) the following?

Code:
#include <cstring> 
using namespace std; 

class Matrix33
{
public:
  Matrix33() : m() {}
private:
  int m[3][3];
}; int main()
{
    int m[3][3], i, j, elem;
    cout<<"Enter the Array Elements: ";
    for(i=0; i<5; i++){ 
        for(j=0; j<5; j++){
                cin>>m[i][j]; 
                cout<<"\nEnter Element to Insert: ";
                cin>>elem;
                m[i][j] = elem;
        } 
    }
    cout<<"\nThe New Array is:\n";
    for(i=0; i<6; i++)
        cout<<m[i][j]<<"  ";
    cout<<endl;
    return 0;
}

:unsure:
 
  • #6
mathmari said:
So do we have at question (a) the following?

Did you try to compile it?
There are a couple of problems with it.
We can try for instance with https://wandbox.org. 🤔

Furthermore, the code you have in main() is not actually using the class Matrix33 is it? 🤔
 
  • #7
Klaas van Aarsen said:
Did you try to compile it?
There are a couple of problems with it.
We can try for instance with https://wandbox.org. 🤔

Furthermore, the code you have in main() is not actually using the class Matrix33 is it? 🤔

I made some changes but I still get errors.

Code:
#include <iostream> 
#include <cstring> 
using namespace std; 

class Matrix33
{
public:
  Matrix33() : m() {}
private:
  int m[3][3];
}; int main()
{
    Matrix33 m[3][3];
    int i, j, elem;
    cout<<"Enter the Array Elements: ";
    for(i=0; i<4; i++){ 
        for(j=0; j<4; j++){
                cin>>m[i][j]; 
                cout<<"\nEnter Element to Insert: ";
                cin>>elem;
                m[i][j] = elem;
        } 
    }
    cout<<"\nThe New Array is:\n";
    for(i=0; i<4; i++){ 
        for(j=0; j<4; j++){
            cout<<m[i][j]<<"  ";
        }  
    } 
    return 0;
}

What else do we have to change? The main is not correct. Normally from the exercise we have to write this in a functionand not in the main, write? :unsure:
 
  • #8
mathmari said:
I made some changes but I still get errors.

What else do we have to change? The main is not correct. Normally from the exercise we have to write this in a function and not in the main, write?

Matrix33 is already a 3x3 matrix, so we shouldn't write Matrix33 m[3][3] but just Matrix33 matrix. 🤔

We need functions in the class to get and set values.
Currently we only have the so called special constructor function Matrix33().
We need for instance int get(int i, int j) { return m[i][j]; } inside the class.
Then we can get the value at position (i, j) with matrix.get(i, j).
Note that we cannot use matrix.m[i][j] since m is private. 🤔

The code to read a matrix from stdin is actually part of (d).
We can keep the code in main() for now to verify that we properly implemented (a).
But it should be replaced when we get to (d). 🤔
 
  • #9
Klaas van Aarsen said:
Matrix33 is already a 3x3 matrix, so we shouldn't write Matrix33 m[3][3] but just Matrix33 matrix. 🤔

We need functions in the class to get and set values.
Currently we only have the so called special constructor function Matrix33().
We need for instance int get(int i, int j) { return m[i][j]; } inside the class.
Then we can get the value at position (i, j) with matrix.get(i, j).
Note that we cannot use matrix.m[i][j] since m is private. 🤔

The code to read a matrix from stdin is actually part of (d).
We can keep the code in main() for now to verify that we properly implemented (a).
But it should be replaced when we get to (d). 🤔
So do we not insert the elements into the matrix with:

Code:
    for(i=0; i<4; i++){ 
        for(j=0; j<4; j++){
                cin>>matrix[i][j]; 
                cout<<"\nEnter Element to Insert: ";
                cin>>elem;
                matrix[i][j] = elem;
        } 
    }

:unsure"
 
  • #10
mathmari said:
So do we not insert the elements into the matrix with:
No. The object matrix does not support indexing with matrix[i][j]. (Shake)

Btw, currently we are first trying to get matrix[i][j], which is not possible.
And then we get elem, which we subsequently try to assign to matrix[i][j].
So we're trying to read every element twice. :eek:
Instead we should just read elem and use for instance matrix.set(i, j, elem) to put it into the matrix. 🤔
 
  • #11
Klaas van Aarsen said:
Instead we should just read elem and use for instance matrix.set(i, j, elem) to put it into the matrix. 🤔

Let's suppose for now that "elem = i+j" then dowe have the following?

Code:
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

class Matrix33
{
private:
    int m[3][3];

public:
    Matrix33(){
        memset(m, 0, sizeof m);
    } 
  
int get(int i, int j) { return m[i][j]; }

void SetCell(int i, int j, int val)
{
    m[i][j] = val;
}

void print()
{
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            cout << m[i][j] << "  ";
        } 
        cout << endl;
    }
}

}; int main()
{
int i,j, elem;
Matrix33 matrix;
for (i=0; i<3; i++){
    for (j=0; j<3; j++){
        elem=i+j;
        matrix.SetCell(i,j,elem); 
    }
}
matrix.print();
return 0;
}

If this is correct then we have to define the correct "elem" and write the main part inside the Class for question (a), or not?

:unsure:
 
Last edited by a moderator:
  • #12
mathmari said:
Let's suppose for now that "elem = i+j" then dowe have the following?

If this is correct then we have to define the correct "elem" and write the main part inside the Class for question (a), or not?
It is fine for (a) as it is now. (Nod)

Just some nitpicks.
The method get() should have a name that matches SetCell().
For (a) we need that "getter" method, so we should call it from main() as well to verify that it works as intended. 🧐
 
  • #13
Klaas van Aarsen said:
The method get() should have a name that matches SetCell().

What do you mean? You mean that they should have a similar name? :unsure:
Klaas van Aarsen said:
For (a) we need that "getter" method, so we should call it from main() as well to verify that it works as intended. 🧐

Do you mean that what I have written in the main should be in a separate function? :unsure:
 
  • #14
mathmari said:
What do you mean? You mean that they should have a similar name?

Do you mean that what I have written in the main should be in a separate function?
Yes. If we have SetCell() to set the value of a cell, then we should have GetCell() to get the value of a cell. 🧐

No. The main() function is fine. It's just that there should be a call to matrix.GetCell() somewhere to verify that it's there and that it works. (a) asks for such a method after all. 🤔
 
  • #15
Klaas van Aarsen said:
Yes. If we have SetCell() to set the value of a cell, then we should have GetCell() to get the value of a cell. 🧐

No. The main() function is fine. It's just that there should be a call to matrix.GetCell() somewhere to verify that it's there and that it works. (a) asks for such a method after all. 🤔

So do we use matrix.GetCell() to print the matrix instead of the function I defined above?

Sodowe do it as follows?

Code:
#include <iostream> 
#include <string> 
#include <cstring>

using namespace std; 

class Matrix33 
{ 
private: 
    int m[3][3]; 

public: 
    Matrix33(){ 
        memset(m, 0, sizeof m); 
    }   
    
int GetCell(int i, int j) { return m[i][j]; } 

void SetCell(int i, int j, int val) 
{
    m[i][j] = val; 
} 

};   int main() 
{ 
int i,j, elem; 
Matrix33 matrix; 
for (i=0; i<3; i++){ 
    for (j=0; j<3; j++){ 
        elem=i+j; 
        matrix.SetCell(i,j,elem);   
        cout << matrix.GetCell(i,j) << "  ";  
    } 
    cout << endl;
} 
return 0; 
}
:unsure:
 
  • #16
mathmari said:
So do we use matrix.GetCell() to print the matrix instead of the function I defined above?
Yep. That works. (Nod)
 
  • #17
Klaas van Aarsen said:
Yep. That works. (Nod)

So all these methods to read and fill the matrix are inside the class Matrix33, right?
How exactly are the elements with which we fill the matrix? Does it mean that that in line $i$ and column $j$ the element that is filled is $ij$ ? :unsure:

The method of part (b) is also inside class Matrix33 ? Or is this a separate method? :unsure:
 
  • #18
mathmari said:
So all these methods to read and fill the matrix are inside the class Matrix33, right?
How exactly are the elements with which we fill the matrix? Does it mean that that in line $i$ and column $j$ the element that is filled is $ij$ ?

The method of part (b) is also inside class Matrix33 ? Or is this a separate method?
The element in line $i$ and column $j$ is filled with $i+j$.
When we run the program that should be visible. 🤔

The word "method" means that it is a function inside a class.
So yes, the method of (b) should be inside class Matrix33. 🤔
 
  • #19
Klaas van Aarsen said:
The element in line $i$ and column $j$ is filled with $i+j$.
When we run the program that should be visible. 🤔

Yes, I wrote in the program to fill the (i,j)-cell with $i+j$, but is this supposed to be like this by the exercise statement? It says "at the positions of tha array according to the line and column of each position.". :unsure:
 
  • #20
mathmari said:
Yes, I wrote in the program to fill the (i,j)-cell with $i+j$, but is this supposed to be like this by the exercise statement? It says "at the positions of tha array according to the line and column of each position.".
It means that we need to have a method that allows us to set the value of a cell at a certain line and column.
The method SetCell() does that.
How it is implemented inside the class is actually arbritrary, as long as we can get the same element back with GetCell() with the same line and column.
And we can. 🤔
 
  • #21
Klaas van Aarsen said:
It means that we need to have a method that allows us to set the value of a cell at a certain line and column.
The method SetCell() does that.
How it is implemented inside the class is actually arbritrary, as long as we can get the same element back with GetCell() with the same line and column.
And we can. 🤔

Do we not havw to ask the user for the enrties of the matrix in (a) ? :unsure:

If yes, is the code as follows?

Code:
#include <iostream> 
#include <string> 
#include <cstring>

using namespace std; 

class Matrix33 
{ 
private: 
    int m[3][3]; 

public: 
    Matrix33(){ 
        memset(m, 0, sizeof m); 
    }   
    
int GetCell(int i, int j) { return m[i][j]; } 

void SetCell(int i, int j, int val) 
{
    m[i][j] = val; 
} 

};   

int main() 
{ 
int i,j, elem; 
Matrix33 matrix; 
for (i=0; i<3; i++){ 
    for (j=0; j<3; j++){ 
        cout<<"Give the (i,j)-element"; 
        cin>>elem; 
        matrix.SetCell(i,j,elem);   
        cout << matrix.GetCell(i,j) << "  ";  
    } 
    cout << endl;
} 
return 0; 
}
:unsure:
 
  • #22
Question (a) does not ask for that, does it? 🤔
 
  • #23
Klaas van Aarsen said:
Question (a) does not ask for that, does it? 🤔

Ah part (d) asks for it. (Malthe)

I tried for part (a) till (c) the following:

Code:
#include <iostream> 
#include <string> 
#include <cstring>

using namespace std; 

//Question (a) 
class Matrix33 
{ 
private: 
    int m[3][3]; 

public: 
    Matrix33(){ 
        memset(m, 0, sizeof m); 
    }   
    
int GetCell(int i, int j) { return m[i][j]; } 

void SetCell(int i, int j, int val) 
{
    m[i][j] = val; 
} 

//Question (b) 
bool isDiagonal()
{
    for (int i = 0; i < 3; i++){ 
        for (int j = 0; j < 3; j++){  
            if ((i != j) && (m[i][j] != 0)){ 
                return false; 
            } 
         } 
    }    
    return true;
} 

//Question (c) 
int Addition(m1[3,3], m2[3,3]) 
{ 
int i,j; 
for (i = 0; i < 3; i++)
        for (j = 0; j < 3; j++)
            m[i][j] = m1[i][j] + m2[i][j];
    cout << "Sum of matrices\n";
    for (i = 0; i < 3; i++)
    {    for (j = 0; j < 3; j++)
            cout << m[i][j] << "  ";    
        cout << "\n";
    } 
}
};
Do we have define m1 and m2 at the beginning at "private" ? :unsure:
 
  • #24
mathmari said:
//Question (c)
Do we have define m1 and m2 at the beginning at "private" ?

Nope. (Shake)

We should define Matrix33 m1, m2 in main().
And we should make sure that we can do Matrix33 m3 = m1 + m2 in main() as well.
We can do so by implementing a function named operator+(). 🤔
 
  • #25
Klaas van Aarsen said:
We should define Matrix33 m1, m2 in main().
And we should make sure that we can do Matrix33 m3 = m1 + m2 in main() as well.
We can do so by implementing a function named operator+(). 🤔

I have done the following for the whole exercise:

Code:
#include <iostream> 
#include <string> 
#include <cstring>

using namespace std; 

//Question (a) 
class Matrix33 
{ 
private: 
    int m[3][3]; 

public: 
    Matrix33(){ 
        memset(m, 0, sizeof m); 
    }   
    
int GetCell(int i, int j) { return m[i][j]; } 

void SetCell(int i, int j, int val) 
{
    m[i][j] = val; 
} 

//Question (b) 
bool isDiagonal()
{
    for (int i = 0; i < 3; i++){ 
        for (int j = 0; j < 3; j++){  
            if ((i != j) && (m[i][j] != 0)){ 
                return false; 
            } 
         } 
    }    
    return true;
} 

//Question (c) 
int OperatorPlus(int x, int y) 
{ 
    int z = x + y; 
    return z;
} 

};   //Question (d) 
int main() 
{ 
int i,j, elem,res; 
Matrix33 m1,m2,m; 
cout << "Enter the elements of matrix m1: ";
for (i=0; i<3; i++){ 
    for (j=0; j<3; j++){ 
       cin>>elem;
       m1.SetCell(i,j,elem);   
       cout << m1.GetCell(i,j) << "  ";  
    } 
    cout << endl;
} 

cout << "Enter the elements of matrix m2: ";
for (i=0; i<3; i++){ 
    for (j=0; j<3; j++){ 
        cin>>elem;
        m2.SetCell(i,j,elem);   
        cout << m2.GetCell(i,j) << "  ";  
    } 
    cout << endl;
} 
        
for (i = 0; i < 3; i++){ 
        for (j = 0; j < 3; j++){ 
            res = OperatorPlus(m1.GetCell(i,j), m2.GetCell(i,j)); 
            m.SetCell(i,j,res); 
        } 
} 
cout << "Sum of matrices\n";
for (i = 0; i < 3; i++){    
    for (j = 0; j < 3; j++){ 
            cout << m[i][j] << "  ";    
    } 
    cout << "\n";
} 
return 0; 
}
I still get some errors. I get:

Code:
prog.cc: In function 'int main()':
prog.cc:75:19: error: 'OperatorPlus' was not declared in this scope
   75 |             res = OperatorPlus(m1.GetCell(i,j), m2.GetCell(i,j));
      |                   ^~~~~~~~~~~~
prog.cc:82:22: error: no match for 'operator[]' (operand types are 'Matrix33' and 'int')
   82 |             cout << m[i][j] << "  ";
      |                      ^

What does these errors mean? Is the rest correct at the code that I wrote? :unsure:
 
  • #26
mathmari said:
Is the rest correct at the code that I wrote?
I don't see the code mentioned in (c). (Shake)

And (d) asks for methods to read and write the matrix. I don't see such methods. (Sweating)

mathmari said:
What does these errors mean?

Code:
prog.cc: In function 'int main()':
prog.cc:75:19: error: 'OperatorPlus' was not declared in this scope
   75 |             res = OperatorPlus(m1.GetCell(i,j), m2.GetCell(i,j));
      |                   ^~~~~~~~~~~~
prog.cc:82:22: error: no match for 'operator[]' (operand types are 'Matrix33' and 'int')
   82 |             cout << m[i][j] << "  ";
      |                      ^
There is no function named 'OperatorPlus'.
Instead Matrix33 has a method with that name.
To call it, we would need for instance int result = matrix.OperatorPlus(2, 3). 🤔

'm' is of type Matrix33. It means that we cannot index it with [i][j]. 🤔
 

1. What is Matrix33 in C++?

Matrix33 in C++ is a data structure used to store a 3x3 matrix of numbers. It is commonly used in computer graphics and linear algebra applications.

2. How do I create a Matrix33 in C++?

To create a Matrix33 in C++, you can use the built-in array data type or the std::array class. You will need to specify the data type and the size of the matrix (3x3).

3. How do I add two Matrix33 in C++?

To add two Matrix33 in C++, you will need to use a nested loop to iterate through each element of the matrices and perform the addition operation. The result will be a new Matrix33 with the sum of the two matrices.

4. How do I check if two Matrix33 are equal in C++?

To check if two Matrix33 are equal in C++, you can compare each element of the matrices using a nested loop. If all elements are equal, then the matrices are considered equal.

5. Can I perform mathematical operations on a Matrix33 in C++?

Yes, you can perform various mathematical operations on a Matrix33 in C++ such as addition, subtraction, multiplication, and division. You can also implement other operations such as finding the determinant or inverse of a Matrix33 using C++.

Similar threads

  • Programming and Computer Science
Replies
31
Views
2K
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
17
Views
1K
  • Programming and Computer Science
Replies
1
Views
944
  • Programming and Computer Science
Replies
4
Views
1K
  • Programming and Computer Science
Replies
15
Views
3K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
20
Views
1K
  • Programming and Computer Science
Replies
17
Views
2K
  • Programming and Computer Science
2
Replies
36
Views
3K
Back
Top