Showing garbage values when adding two matrix using operator overloading - c++

Please help me as I am new to programming and I have made this program and it looks fine to me but I am getting garbage values instead of sum of two matrix.I have applied the concept of operator overloading to find the sum of two matrices but I am getting garbage values again and again?Please help me that where is the problem?Thanks.Any help is completely appreciated
#include<iostream>
#include<string>
using namespace std;
class Matrix {
private:
int matrix[2][2];
public:
Matrix operator + (Matrix Sum)
{
Matrix sum[2][2];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
sum[i][j].matrix[i][j] = matrix[i][j] + Sum.matrix[i][j];
return(sum[i][j]);
}
}
}
void setMatrix(int m[][2])
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
matrix[i][j] = m[i][j];
}
}
}
void Display()
{
cout << "\n\nThe matrix finally equals: ";
for (int i = 0; i < 2; i++)
{
cout << " ";
for (int j = 0; j < 2; j++)
{
cout<<matrix[i][j];
if (j == 2 - 1)
cout << endl;
}
}
}
};
int main()
{
Matrix m1, m2,sum;
const int size=2;
int matrix1[size][size];
int matrix2[size][size];
cout << "Enter the values of matrix 1 (2 X 2)\n\n";
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
cin >> matrix1[i][j];
}
}
cout << "Enter the values of matrix 2 (2 X 2)\n\n";
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
cin >> matrix2[i][j];
}
}
cout <<"\n\nSetting the values now\n\n";
m1.setMatrix(matrix1);
m2.setMatrix(matrix2);
sum = m1 + m2;
cout << "\n\nMatrix 1 (2 X 2) is : ";
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
cout << matrix1[i][j] << " ";
if (j == size - 1)
cout << endl;
}
}
cout << "\n\nMatrix 2 (2 X 2) is : ";
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
cout << matrix2[i][j] << " ";
if (j == size - 1)
cout << endl;
}
}
cout << "\n\nSum of two matrices is equal to (2 X 2) is : ";
sum.Display();
return 0;
}

Let's take a close look at you operator+, there are two major errors:
Matrix sum[2][2]; is an array of matrices, but you want to return only a single Matrix, not multiple. Also the name is bad, because you already have a parameter with a similiar name. And yes, C++ is case sensitive, but such similiar names are problematic for human readers ;).
Look where the return is. It will return during the first iteration, e.g.
sum[i][j].matrix[i][j] = matrix[i][j] + Sum.matrix[i][j];
will be called just once, with i and j being zero. Thus it sets only one entry and returns immediately afterwards (leaving the other 3 values uninitialized). That's where the garbage values come from, technically it's undefined behaviour.
Here is what the function should look like, but please don't just copy-paste, but take some time to understand it.
Matrix operator + (Matrix rhs) // One of the two names needed to change.
{
Matrix sum; //only one value with a proper name
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
// better be explicit and use this, imo
sum.matrix[i][j] = this->matrix[i][j] + rhs.matrix[i][j];
}
}
return sum; // return only after all the calculations.
}

Related

What happens with the dynamic memory allocation, of a matrix with different size of columns on each line?

I'm trying to create a matrix in C++, having a shape of a triangle like this :
n = number of lines;
If i input n = 4, for example, my matrix should look like this :
1
23
456
78910
I've managed to do the following code :
int n;
cout << "Introduceti n: ";
cin >> n;
int** a = new int*[n];
for (int i = 0; i < n; i++) {
a[i] = new int[i+1];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < i+1; j++) {
*(*(a + i) + j) = (i * i + i) / 2 + j +1;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < i+1; j++) {
cout << *(*(a + i) + j) << "|";
}
cout << endl;
}
The question is : why can i access a[0][1] and it shows me a value, if i instructed my pointer to stop initializing at a[0][0] ?
You can access memory, regardless of it being initialized or allocated.
It is up to you to code avoiding those likely unwanted events, or having mechanisms in place to detect them.
So,
why can i access a[0][1]...
As said above
... and it shows me a value, ...
Because every bit in memory has some value.
Try code below, and you will probably understand what you are doing.
The least memory you can take is by ensuring you have contiguous allocation. So you would rather allocate storage in a linear array for (n*(n+1)/2) ints (the size of your triangular matrix), and then simply define functions/macros for accessing element (i,j). It may take not more than 20 lines of code... if you want to work fail-safe, you can include a few checks for a couple more lines.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Introduceti n: ";
cin >> n;
int **a = new int*[n];
for (int i = 0; i < n; i++) {
a[i] = new int[i + 1];
}
cout << "Size of int is " << sizeof(int) << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i + 1; j++) {
*(*(a + i) + j) = (i * i + i) / 2 + j + 1;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < i + 1; j++) {
cout << *(*(a + i) + j) << "|";
}
cout << endl;
}
cout << "a[0][0] #" << &(a[0][0]) << "=" << a[0][0] << endl;
cout << "a[0][1] #" << &(a[0][1]) << "=" << a[0][1] << endl;
return 1;
}

Swapping elements in 2d array

So, I'm trying to swap the matrix elements with respect to the main diagonal. I have tried using temp method (switching values while using temp variable), also tried std::swap(a,b). Somehow it only swaps upper right side of the matrix and leaves another half not changed.
How do I make everything swap?
My code:
#include <iostream>
using namespace std;
int main()
{
const int n = 7;
srand (time(NULL));
int matrix[n][n];
cout << "Original Matrix :" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
(i == j) ? matrix[i][j] = 0 : matrix[i][j] = rand() % 100+1;
cout << matrix[i][j] << "\t";
}
cout << endl;
}
cout << "\nRemade Matrix:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
// swap(matrix[i][j], matrix[j][i]); //another method
cout << matrix[i][j] << "\t";
}
cout << endl;
}
return 0;
}
You are basically swapping them twice, replace your swapping loops with this. Notice the condition of the second loop, it's j < i. Then, you can print it with another set of loops.
for (int i = 0; i < n; i++)
for (int j = 0; j < i ; j++)
swap(matrix[i][j], matrix[j][i]);
Your logic is almost ok. Just the inner loop counter will start from "i+1" else after the swapping the value is again getting overlapped. Try the following code and make sure you understand it. Happy coding!
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << matrix[i][j] << "\t";
}
cout << endl;
}

How do I set all the diagonals in a matrix equal to zero?

I have a problem with my homework that asks me to have the compiler print out a matrix in which all the diagonals are outputted as zero. I also have to pass it to a function. However, I have no idea how to do this..
Here is my code:
#include <iostream>
using namespace std;
int diagonals();
int main()
{
//problem 1
int matrix[3][3];
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3 ; j++)
{
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "\nReverse of the matrix:" << endl;
for (int j = 1; j <= 3; j++)
{
for (int i = 1; i <= 3; i++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}//end of problem 1
//problem 2
cout << "Diagonals changed to 0:\n" << endl;
}
your matrix declaration says int matrix[3][3]; that it has three 1-D array & in each 1-D array you can store three elements. And in C/C++ array index starts from zero.
Problematic statement is for (int i = 1; i <= 3; i++) as you are skipping matrix[0][0] and trying to store into matrix[3][3] which doesn't exist which in turn causes undefined behavior.
So firstly start iterating loop from 0 to number of rows & column respectively.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 ; j++) {
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
Coming to task you mentioned, print out a matrix in which all the diagonals are outputted as zero. ? write one condition so that if row value & col value are equal then assign it to zero otherwise scan from user. Here is the sample code
int main(void) {
int matrix[3][3] = { 0 }; /* initialize it */
int row = sizeof(matrix)/sizeof(matrix[0]); /* find no of rows */
int col = sizeof(matrix[0])/sizeof(matrix[0][0]);/* find no of columns */
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if( i == j)
matrix[i][j] = 0;/* when i and j are equal means thats diagonal and assign it to zero */
else /* if its not diagonal then scan from user */
std::cin>>matrix[i][j];
}
}
return 0;
}
Secondly, I also have to pass it to a function. for this learn how to pass 2d array to a function. Here is the sample example.
void diagonal(int (*mat)[3],int row, int col) { /* mat is pointer to an array */
std::cout<<"printing matrix "<<std::endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
std::cout<<mat[i][j]<<"\t";
}
std::cout<<std::endl;
}
}
And call diagonal() like below from main() function as
diagonal(matrix,row,col); /* pass matrix, no of rows, no of columns */

How do i add all the values in my ascending array?

First i need to re-arrange all the values of my array into ascending order then add it afterwards. For example the user input 9 2 6, it will display in ascending order first ( 2 6 9 ) before it will add the sum 2 8 17.. The problem is my ascending order is not working, is there something wrong in my code?
#include <iostream>
#include<conio.h>
using namespace std;
int numberof_array, value[10], temp;
int i = 0, j;
void input()
{
cout << "Enter number of array:";
cin >> numberof_array;
for (i = 0; i < numberof_array; i++)
{
cout << "Enter value for array [" << i + 1 << "] - ";
cin >> value[i];
cout << endl;
}
}
void computation()
{
// this is where i'll put all the computation
for (j = 0; j < numberof_array; j++)
{
cout << value[j];
}
for (i = 0; i <= numberof_array; i++)
{
for (j = 0; j <= numberof_array - i; j++)
{
if (value[j] > value[j + 1])
{
temp = value[j];
value[j] = value[j + 1];
value[j + 1] = temp;
}
}
}
}
void display()
{
// display all the computation i've got
cout << "\nData after sorting: ";
for (j = 0; j < numberof_array; j++)
{
cout << value[j];
}
getch();
}
int main()
{
input();
computation();
display();
}
void computation(){
for (int j = 0; j < numberof_array; j++) cout << value[j]<<"\t";
for (int i = 0; i <= numberof_array; i++) {
temp = value[i];
int temp_idx = i;
for (int j = i; j < numberof_array; j++) {
if (value[j] < temp) {
temp = value[j];
temp_idx = j;
}
}
int temp_swap = value[i];
value[i] = value[temp_idx];
value[temp_idx] = temp_swap;
}
}
How about changing your second function to something like above.
I have to agree with other commentators that your coding style is not preferred but there might be more to the story than meets the eye.

What is “Asymptotically tight time complexity”? Is this code's time complexity asymptotically tight?

Why is the time complexity of this code O(xnm)?
Is this code's time complexity asymptotically tight?
Why?
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
int a[10][10], b[10][10], c[10][10];
int x, y, i, j, m, n;
cout << "\nEnter the number of rows and columns for Matrix A:::\n\n";
cin >> x >> y;
// x denotes number rows in matrix A
// y denotes number columns in matrix A
cout << "\n\nEnter elements for Matrix A :::\n\n";
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
cin >> a[i][j];
}
cout << "\n";
}
cout << "\n\nMatrix A :\n\n";
for (i = 0; i < x; i++)
{
for (j = 0; j < y; j++)
{
cout << "\t" << a[i][j];
}
cout << "\n\n";
}
cout << "\n-----------------------------------------------------------\n";
cout << "\nEnter the number of rows and columns for Matrix B:::\n\n";
cin >> m >> n;
// m denotes number rows in matrix B
// n denotes number columns in matrix B
cout << "\n\nEnter elements for Matrix B :::\n\n";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
cin >> b[i][j];
}
cout << "\n";
}
cout << "\n\nMatrix B :\n\n";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
cout << "\t" << b[i][j];
}
cout << "\n\n";
}
if (y == m)
{
for (i = 0; i < x; i++)
{
for (j = 0; j < n; j++)
{
c[i][j] = 0;
for (int k = 0; k < m; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
cout
<< "\n-----------------------------------------------------------\n";
cout << "\n\nMultiplication of Matrix A and Matrix B :\n\n";
for (i = 0; i < x; i++)
{
for (j = 0; j < n; j++)
{
cout << "\t" << c[i][j];
}
cout << "\n\n";
}
}
else
{
cout << "\n\nMultiplication is not possible";
}
getch();
return 0;
}
Because the most computations is done here:
for (i = 0; i < x; i++)
{
for (j = 0; j < n; j++)
{
c[i][j] = 0;
for (int k = 0; k < m; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
The approximation of number of basic operations like addition, multiplication and assignment here is x*n*m. That is why this algorithm has O(x*n*m) asymptotic. But matrix multiplication can be done faster in terms of asymptotic. Just check out related articles about matrix multiplication and big o notation.
Complexity introduction
Faster matrix multiplication approach