I wrote a program to add two matrices. The program I wrote takes in the number of rows and columns (max columns is 50) and then adds them. The 2D arrays required are initialized dynamically. However, the debugger is giving me an error in the addition part. Here's my code:
#include <iostream> #include <iomanip> #include <conio.h> #include <cstring> using namespace std; int main() { int rows1, columns1, cout << "Enter the number of rows: "; cin >> rows1; cout << "Enter the number of columns (max 50): "; cin >> columns1; if(columns1 > 50) { cout << "Columns cannot be more than 50."; exit(0); } int* matrix1 = new int[rows1*50]; // Create a 2D array of size [rows][50] // Input first matrix for(int i = 0; i < rows1; i++) { for(int j = 0; j < columns1; j++) { cout << "Enter A[" << i + 1 << "][" << j + 1 << "]: "; cin >> matrix1[i*50 + j]; // For 2D arrays, a[i][j] is a[i*columns + j] } } // Show matrix A to user for(int i = 0; i < rows1; ++i) { cout << endl; for(int j = 0; j < columns1; ++j) cout << " " << matrix1[i*50 + j]; } cout << endl << endl; // Input second matrix int* matrix2 = new int[rows1*50]; for(int i = 0; i < rows1; i++) { for(int j = 0; j < columns1; j++) { cout << "Enter B[" << i + 1 << "][" << j + 1 << "]: "; cin >> matrix2[i*50 + j]; } } // Show matrix B to user for(int i = 0; i < rows1; ++i) { cout << endl; for(int j = 0; j < columns1; ++j) cout << " " << matrix2[i*50 + j]; } // Make a new matrix of same size to hold the finished array int* matrix3 = new int[rows1*50]; for(int i = 0; i < rows1; ++i) { for(int j = 0; j < columns1; ++j) matrix3[i*50 + j] = matrix1[i*50 + j] + matrix2[i*50 + j]; } cout << "The result is: \n"; // Show resultant matrix to user for(int i = 0; i < rows1; ++i) { cout << endl; for(int j = 0; j < columns1; ++j) cout << " " << matrix3[i*50 + j]; } delete [] matrix1; delete [] matrix2; delete [] matrix3; matrix1 = nullptr; matrix2 = nullptr; matrix3 = nullptr; _getch(); return 0; }
I'm getting the error in the second last for loop - where the actual adding takes place
Thanks,
Rahul