Whats Wrong In This Code......HELP

Create a class Matrix and Write a C++ program to perform the following functions:
a. To accept a Matrix
b. To display a Matrix
c. Overload unary minus „–„ operator to calculate transpose of a Matrix
d. Overload binary multiplication '*‟ operator to calculate multiplication of two matrices

So This Is My Assignment Question
I don't Know Why My Code Is Not Working
And Whats Should Be right Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include<iostream>
#include<stdlib.h>
using namespace std;

int a,b;

class Matrix
{
    public:
    int **A;
    int m,n;
public:
    Matrix(int a,int b)
    {
        m=a;
        n=b;
        A=new int*[m];
        for(int i=0;i<m;i++)
        {
            A[i]=new int[n];
        }
    }

    ~Matrix()
    {
        for(int i=0;i<m;i++)
        {
            delete[] A[i];
        }
        delete[] A;
    }

    void accept()
    {
        cout<<"\nEnter The Matrix Elements:\n";
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
        {
            cout<<"Matrix["<<i<<"]["<<j<<"]:";
            cin>>A[i][j];
        }
    }

    void display()
    {
        cout<<"\nEntered Matrix Elements Are:\n";
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
        {
            cout<<"\nMatrix["<<i<<"]["<<j<<"]:";
            cout<<A[i][j];
        }
    }

    Matrix operator *(Matrix M2)
    {
        Matrix Mult(a,b);
        for(int i=0;i<a;i++)
            for(int j=0;j<b;j++)
        {
            Mult.A[i][j]=0;
        }
        for(int i=0;i<a;i++)
            for(int j=0;j<b;j++)
        {
            Mult.A[i][j]+=A[i][j]*M2.A[j][i];
        }
        return Mult;
    }

    Matrix operator -()
    {
        Matrix Temp(a,b);
        for(int i=0;i<a;i++)
            for(int j=0;j<b;j++)
        {
            Temp.A[i][j]=A[j][i];
        }
        return Temp;
    }
};

int main()
{
    int ch;
    while(1)
    {
        cout<<"\n\n----MENU----";
        cout<<"\n1.Multiplication Of Matrices";
        cout<<"\n2.Transpose Of Matrix";
        cout<<"\n3.Exit";
        cout<<"\n\nEnter Your Choice:";
        cin>>ch;
        switch(ch)
        {
        case 1:
            {
                cout<<"\nEnter Matrices Rows And column:";
                cin>>a>>b;
                while(a!=b)
                {
                    cout<<"\nPlz Enter The rows And Columns Same";
                    cout<<"Again Enter Matrices Rows And column Same:";
                    cin>>a>>b;
                }
                Matrix M1(a,b),M2(a,b);
                cout<<"\nEnter 1st Matrices Elements:";
                M1.accept();
                M1.display();
                cout<<"\nEnter 2nd Matrices Elements:";
                M2.accept();
                M2.display();
                Matrix Mult(a,b);
                {
                    for(int i=0;i<a;i++)
                        for(int j=0;j<b;j++)
                    {
                        Mult.A[i][j]=0;
                    }
                }
                Mult=M1*M2;
                cout<<"\nBoth Multiplied Matrices Are:";
                Mult.display();
                break;
            }

        case 2:
            {
                cout<<"\nEnter Matrices Rows And column:";
                cin>>a>>b;
                Matrix M(a,b);
                M.accept();
                M.display();
                Matrix Temp(a,b);
                Temp=-M;
                cout<<"\nTranspose Of Matrix Is:";
                Temp.display();
                break;
            }

        case 3:
            exit(1);

        default :
            cout<<"Invalid Choice!!!";
            break;
        }
    }
}


Plz Feel Free To Suggest Anything
Thank You
In what way is it "not working"?
My first suggestion is that you increase your compiler warning levels and fix any and all warnings. This is what my compiler says about your code:

||=== Build: Debug in c++homework (compiler: GNU GCC Compiler) ===|
main.cpp|7|warning: ‘class Matrix’ has pointer data members [-Weffc++]|
main.cpp|7|warning: but does not override ‘Matrix(const Matrix&)’ [-Weffc++]|
main.cpp|7|warning: or ‘operator=(const Matrix&)’ [-Weffc++]|
main.cpp||In constructor ‘Matrix::Matrix(int, int)’:|
main.cpp|14|warning: declaration of ‘b’ shadows a global declaration [-Wshadow]|
main.cpp|5|note: shadowed declaration is here|
main.cpp|14|warning: declaration of ‘a’ shadows a global declaration [-Wshadow]|
main.cpp|5|note: shadowed declaration is here|
main.cpp|13|warning: ‘Matrix::A’ should be initialized in the member initialization list [-Weffc++]|
main.cpp|13|warning: ‘Matrix::m’ should be initialized in the member initialization list [-Weffc++]|
main.cpp|13|warning: ‘Matrix::n’ should be initialized in the member initialization list [-Weffc++]|
||=== Build finished: 0 error(s), 8 warning(s) (0 minute(s), 0 second(s)) ===|


Those first two warnings are probably a part of your problem since you seem to be trying to use at least one of them.

You should also get rid of those horrible global variables.

Lastly, for now, you need to use more descriptive variable and function names.

So I Have Changed My Code But Its Still Not Working
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include<iostream>
#include<stdlib.h>
using namespace std;

class Matrix
{
    public:
    int **A;
    int m,n;
public:
    Matrix(int a,int b)
    {
        m=0;
        n=0;
        m=a;
        n=b;
        A=new int*[m];
        for(int i=0;i<m;i++)
        {
            A[i]=new int[n];
        }
    }

    ~Matrix()
    {
        for(int i=0;i<m;i++)
        {
            delete[] A[i];
        }
        delete[] A;
    }

    void accept()
    {
        cout<<"\nEnter The Matrix Elements:\n";
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
        {
            cout<<"Matrix["<<i<<"]["<<j<<"]:";
            cin>>A[i][j];
        }
    }

    void display()
    {
        cout<<"\nEntered Matrix Elements Are:\n";
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
        {
            cout<<"\nMatrix["<<i<<"]["<<j<<"]:";
            cout<<A[i][j];
        }
    }

    Matrix operator *(Matrix M2)
    {
        int a,b;
        a=m;
        b=n;
        Matrix Mult(a,b);
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
        {
            Mult.A[i][j]=0;
        }
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
        {
            Mult.A[i][j]+=A[i][j]*M2.A[j][i];
        }
        return Mult;
    }

    Matrix operator -()
    {
        int a,b;
        a=m;
        b=n;
        Matrix Temp(a,b);
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
        {
            Temp.A[i][j]=A[j][i];
        }
        return Temp;
    }
};

int main()
{
    int ch,a,b;
    while(1)
    {
        cout<<"\n\n----MENU----";
        cout<<"\n1.Multiplication Of Matrices";
        cout<<"\n2.Transpose Of Matrix";
        cout<<"\n3.Exit";
        cout<<"\n\nEnter Your Choice:";
        cin>>ch;
        switch(ch)
        {
        case 1:
            {
                cout<<"\nEnter Matrices Rows And column:";
                cin>>a>>b;
                while(a!=b)
                {
                    cout<<"\nPlz Enter The rows And Columns Same";
                    cout<<"Again Enter Matrices Rows And column Same:";
                    cin>>a>>b;
                }
                Matrix M1(a,b),M2(a,b);
                cout<<"\nEnter 1st Matrices Elements:";
                M1.accept();
                M1.display();
                cout<<"\nEnter 2nd Matrices Elements:";
                M2.accept();
                M2.display();
                Matrix Mult(a,b);
                {
                    for(int i=0;i<a;i++)
                        for(int j=0;j<b;j++)
                    {
                        Mult.A[i][j]=0;
                    }
                }
                Mult=M1*M2;
                cout<<"\nBoth Multiplied Matrices Are:";
                Mult.display();
                break;
            }

        case 2:
            {
                cout<<"\nEnter Matrices Rows And column:";
                cin>>a>>b;
                Matrix M(a,b);
                M.accept();
                M.display();
                Matrix Temp(a,b);
                Temp=-M;
                cout<<"\nTranspose Of Matrix Is:";
                Temp.display();
                break;
            }

        case 3:
            exit(1);

        default :
            cout<<"Invalid Choice!!!";
            break;
        }
    }
}


Could You Just Help Me Write The Right Code And Explain Me The Errors, Warnings?
That would be appreciated
Thank You


and btw I can't Understand The First Two Warnings
Could You Just Help Me Write The Right Code And Explain Me The Errors, Warnings?


I have learned from these guys that such a request is NOT appreciated.

I cannot help with the actual code, but I (think) what will help them is to use a separate code tag for the class and the main function.

Next, use comments to explain what is happening. At least use comments to separate parts of your code like this: //-------------------------------

Shouldn't you do
1
2
3
4
cout<<"\n\n----MENU----";
        cout<<"\n1.Multiplication Of Matrices";
        cout<<"\n2.Transpose Of Matrix";
        cout<<"\n Or press any key to exit.";


And then remove the case 3 and choose default case as:
1
2
default :
            exit(0);

?

Line 114 and 115 are kinda repetitive. You can ask them to put their numbers using spaces (Putting spaces makes the program treat them as separate integers), and to use Enter when they change the row.
And change input to
1
2
3
4
5
6
7
8
9
10
void setvalues(){
			cout<<"Enter elements of your Matrix (Put space between numbers of the same row): \n";
			for(int i=0;i<rows;i++)
			{
				for(int j=0;j<cols;j++)
				{
					cin>>matrix[i][j];
				}
			}
		}


Although data representation is entirely up to you.


My own personal question to someone more experienced:
1. What is up with line 13 & 14? What if he does not initialize to zero?
Also similarly in line 64. But not in line 79

2. In line 17, is it a good programming practice to use dynamic memory allocation instead of a multidimensional array as a data member? What advantages does it offer?
a) Why did OP seemingly only allocate to a single-dimnsional array?

3. In line 8, what does a double asterisk mean?

4. How did he multiply? Can someone please expand line 69? I mean we are supposed to do
Answer(0,0) = First(0,0)*Second(0,0) + First(0,1)*Second(1,0)
right?
But according to line 67-69, when i = 0, j = 1 ; Then we have
Answer(0,1) = First(0,1)*Second(1,0)


5.
You have pointer member variables so you need to overload the copy constructor and the operator=.



My own personal question to someone more experienced:
1. What is up with line 13 & 14?

What post are you talking about, it would be better if you actually showed the code as well as the line numbers.

2. In line 17, is it a good programming practice to use dynamic memory allocation instead of a multidimensional array as a data member? What advantages does it offer?

He is using dynamic memory allocation instead of the statically allocated array because he doesn't know the sizes of the array at compile time. But really he should be considering std::vectors instead of the arrays.

a) Why did OP seemingly only allocate to a single-dimnsional array?

Actually he did allocate memory for a multidimensional array:
1
2
3
4
5
        A=new int*[m];  // Allocate memory for the outer dimension (with a size of m).
        for(int i=0;i<m;i++)
        {
            A[i]=new int[n]; // Allocate an array (with a size of n) for each element of the outer array.
        }


3. In line 8, what does a double asterisk mean?

It means a pointer to a pointer of int.

So, Guys, I Have Changed My Entire code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include<iostream>
#include<stdli.h>
using namespace std;

class Matrix
{
    public:
    int A[100][100];
    int m,n;
public:
    Matrix(int a,int b)
    {
        m=a;
        n=b;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                A[i][j]=0;
            }
        }
    }

    Matrix()
    {
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                A[i][j]=0;
            }
        }
    }

    void accept()
    {
        cout<<"\nEnter The Matrix Row And Column:";
        cin>>m>>n;
        while(m!=n)
        {
            cout<<"\nPlz Enter The Number Of Rows And column Same:";
            cout<<"\nEnter The Matrix Row And Column Again:";
            cin>>m>>n;
        }
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                cout<<"Matrix["<<i<<"]["<<j<<"]:";
                cin>>A[i][j];
            }
        }
    }

    void display()
    {
        cout<<"\n Your Entered Matrix Is:";
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                cout<<"\nMatrix["<<i<<"]["<<j<<"]:";
                cout<<A[i][j];
            }
        }
    }

    Matrix operator*(Matrix M2)
    {
        Matrix M3(m,n);
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                M3.A[i][j]+=A[i][j]*M2.A[j][i];
            }
        }
        return M3;
    }

    Matrix operator -()
    {
        Matrix Temp(m,n);
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                Temp.A[i][j]=A[j][i];
            }
        }
        return Temp;
    }
};

int main()
{
    int ch,a,b;
    while(1)
    {
        cout<<"\n\n****MENU****";
        cout<<"\n1.Multiplication Of Two Matrices";
        cout<<"\n2.Transpose Of Matrix";
        cout<<"\n3.Exit";
        cout<<"\nEnter Your Choice:";
        cin>>ch;
        switch(ch)
        {
            case 1:
                    {
                        Matrix M1,M2;
                        cout<<"\nEnter Your 1st Matrix:";
                        M1.accept();
                        M1.display();
                        cout<<"\nEnter Your 2st Matrix:";
                        M2.accept();
                        M2.display();
                        a=M1.m;
                        b=M1.n;
                        Matrix M3(a,b);
                        M3=M1*M2;
                        cout<<"\nYour Multiplied Matrix Is:";
                        M3.display();
                        break;
                    }

            case 2:
                    {
                        Matrix M4;
                        M4.accept();
                        M4.display();
                        a=M4.m;
                        b=M4.n;
                        Matrix M5(a,b);
                        cout<<"\nYour Transposed Matrix Is:";
                        M5=-M4;
                        M5.display();
                        break;
                    }
       case 3:
                exit(1);
            default :
                    cout<<"\nInvalid Choice!!!";
                    break;
        }
    }
}


And The Code Still Not Working
and Yes I am Not Yet Familiar With std::vectors(I am Just A beginner)
(Both The Cases doesn't Give You The Right Output)
Last edited on
And The Code Still Not Working

Please explain exactly what you mean by the above.

Yes I am Not Yet Familiar With std::vectors(I am Just A beginner)

What does not knowing about vectors have to do with being a beginner?

(Both The Cases doesn't Give You The Right Output)


Again what exactly does this mean? Show your input and the output of the program and what you expect the output to be with that input.

Do you realize that:
1
2
3
4
5
6
7
8
9
10
    Matrix()
    {
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                A[i][j]=0;
            }
        }
    }

is producing undefined behavior because both m and n are undefined? Perhaps you need to first assign a value to m and n (100 perhaps)?

Or do something like:

Matrix() : A{0}, m(100), n(100)
{
// Blank body.
}


And since you seem to want both m and n to be the same (see you accept() function) why even have two variables at all? By the way what is the meaning of m and n in this content?

And The Code Still Not Working

That could be the name of your autobiography.
Last edited on
My own personal question to someone more experienced:
1. What is up with line 13 & 14? What if he does not initialize to zero?
Also similarly in line 64. But not in line 79

If you don't set them to 0, they will carry garbage values. It would make debugging what the source of a potential error is harder when you're seeing random numbers rather than just 0s if you happen to not set the values. However, in this case, it's not needed since he overwrites it with the values he takes in anyway.

Moreover, setting to 0 is more important for the array on line 64 since you may not give a value to every element in the array. If you don't want to use any of the numbers in the array you haven't inputted, it would be practically stupid or highly tedious to try and figure out which elements are ones you've inputted and which were garbage values. It's a lot easier to recognize which values you've set when all other values are simply 0.

2. In line 17, is it a good programming practice to use dynamic memory allocation instead of a multidimensional array as a data member? What advantages does it offer?
a) Why did OP seemingly only allocate to a single-dimnsional array?

You can't make any array without first knowing the size beforehand. A dynamically allocated array lets you make an array size that is only known during run-time. Vectors allow this too and are usually recommended over trying to manage your own memory.

The OP seemingly wanted to allocate a 2D array, but instead allocated a 1D array of pointers (which he fixed in his most recently submitted code).


How did he multiply? Can someone please expand line 69? I mean we are supposed to do

It's his logic, no idea what he wanted to do. He's just multiplying the numbers and adding them together then storing the answer into another array.
Last edited on
Hacked up simplistic example of using a 2D vector to store and display the data elements of your matrix:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <vector>

class Matrix
{
private:
   // empty 2D vector member data, add rows and columns later
   std::vector<std::vector<int>> myMatrix;

   // member data for the Matrix rows and columns, defaulted to zero
   unsigned m_rows { };
   unsigned m_cols { };

public:
   // override the compiler wanting to add a no parm ctor, deleting so it can't be called
   Matrix() = delete;

   // create a Matrix with given number of rows and columns
   Matrix(unsigned rows, unsigned cols) : m_rows(rows), m_cols(cols)
   {
      // loop for the number of rows to populate the Matrix
      for (unsigned row { }; row < rows; row++)
      {
         // create a temp 1D vector of cols size (number of columns)
         // each row will be zero filled by default
         std::vector<int> temp(cols);

         // add each new row to the Matrix
         myMatrix.push_back(temp);
      }
   }

   // no need to manually delete the 2D vector in the dtor
   ~Matrix() {}

public:
   // add some member functions to add/change the Matrix element data
   // and to transpose a Matrix and multiply 2 Matrices

public:
   void Display() const;
};

int main()
{
   // let's create a 3 (rows) x 4 (columns) Matrix
   // it will be zero-filled by default
   Matrix myMat(3, 4);

   // let's display the bugger
   myMat.Display();
   std::cout << '\n';

   Matrix myMat2(5, 8);
   myMat2.Display();
}

void Matrix::Display() const
{
   if (m_rows == 0) // empty Matrix!!!!!
   {
      std::cout << "**** Empty Matrix, nothing to display!!!!! ****\n\n";
      return;
   }

   // loop the rows
   for (unsigned row { }; row < m_rows; row++)
   {
      // display an opening marker each row for matrix notation
      std::cout << "[ ";

      // loop the columns
      for (unsigned col { }; col < m_cols; col++)
      {
         // display each 2D vector element with a space
         std::cout << myMatrix[row][col] << ' ';
      }

      // display a closing marker for each row and a newline
      std::cout << "]\n";
   }
}

[ 0 0 0 0 ]
[ 0 0 0 0 ]
[ 0 0 0 0 ]

[ 0 0 0 0 0 0 0 0 ]
[ 0 0 0 0 0 0 0 0 ]
[ 0 0 0 0 0 0 0 0 ]
[ 0 0 0 0 0 0 0 0 ]
[ 0 0 0 0 0 0 0 0 ]
@OP
Lines like M5=-M4; don't produce anything without an assignment operator. If you do that the transpose function works.


So your first step is to write an assignment operator. Since you have written the rest of the code then it won't present any sort of a challenge.

Just in case though, here's a start:

1
2
3
4
5
6
Matrix operator=(Matrix M2)
    {
        Matrix M3(???);
        // ... a handful of lines go here
        return M3;
    }


****MENU****
1.Multiplication Of Two Matrices
2.Transpose Of Matrix
3.Exit
Enter Your Choice:2

Enter The Matrix Row And Column:2 2
Matrix[0][0]:1
Matrix[0][1]:2
Matrix[1][0]:3
Matrix[1][1]:4

 Your Entered Matrix Is:
Matrix[0][0]:1
Matrix[0][1]:2
Matrix[1][0]:3
Matrix[1][1]:4
Your Transposed Matrix Is:
 Your Entered Matrix Is:
Matrix[0][0]:1
Matrix[0][1]:3
Matrix[1][0]:2
Matrix[1][1]:4
 Your Entered Matrix Is:
Matrix[0][0]:0
Matrix[0][1]:0
Matrix[1][0]:0
Matrix[1][1]:0

****MENU****
1.Multiplication Of Two Matrices
2.Transpose Of Matrix
3.Exit
Enter Your Choice:
Last edited on
OOP's (object-oriented blooper, that is) I nearly forgot. Your transpose function has got the wrong arrangement of row/col indices.
Last edited on
Lines like M5=-M4; don't produce anything without a copy constructor.

Actually that's not quite true for a couple of reasons.

The problems are that without the copy constructor and the overloaded assignment operator a shallow copy (the pointer is copied, not the actual data) constructor/operator= is created and if you have pointer member variables you need to provide deep copy by copying the actual data instead of just the pointer.
Looking at your most recent code:

Line 2 should be #include <cstdlib>

Default constructor: As someone else pointed out, you have to initialize m and n.

accept() method: If m and n must be the same (i.e., if you only support square matrices) then why not just store the number once in n? You don't need m at all.

operator-() Look carefully at your code. Nowhere do you subtract anything from anything. Is this really supposed to transpose the matrix? It seems like operator-() should negate each value in the matrix instead.
Topic archived. No new replies allowed.