C++ Program with matrix class ending abruptly - c++

I am writing a matrix class where I need to perform some matrix calculations in the main program. I am not sure why the program is ending abruptly when user chooses a matrix of size more than 2x2 matrix. The std::cin works fine until two rows but program ends after the loop reaches third row. Only part of the code is shown below which is related to my question.
#include<iostream>
#include <vector>
#include <cassert>
using std::vector;
using namespace std;
class Matrix {
private:
int rows;
int cols;
int **vtr;
public:
Matrix(int m = 2, int n = 2)
{
rows = m;
cols = n;
vtr = new int*[m];
for (int i = 0; i < m; i++)
{
vtr[i] = new int [n];
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
vtr[i][j] = 0;
}
}
}
void read()
{
cout << "Enter the number of rows and columns of Matrix separated by a space: ";
cin >> rows >> cols;
Matrix a(rows, cols);
a.write();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << "(" << i << "," << j << ") : ";
cin >>vtr[i][j];
}
}
}
void write()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << vtr[i][j] << " ";
}
cout << endl;
}
cout << endl << endl;
}
};
int main()
{
Matrix A, B, C;
int row, column ;
cout << "For Matrix A" << endl;
A.read();
cout << "For Matrix B " << endl;
B.read();
cout << "For Matrix C" << endl;
C.read();
}

Since the 2D array, vtr is created when declaring the Matrix object, you can move the vtr creation after reading the console input like below.
Matrix(int m = 2, int n = 2)
{
/*rows = m;
cols = n;
vtr = new int*[m];
for (int i = 0; i < m; i++)
{
vtr[i] = new int [n];
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
vtr[i][j] = 0;
}
}*/
}
void read()
{
cout << "Enter the number of rows and columns of Matrix separated by a space: ";
cin >> rows >> cols;
vtr = new int*[rows];
for (int i = 0; i < rows; i++)
{
vtr[i] = new int [cols];
}
//Matrix a(rows, cols);
//write();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << "(" << i << "," << j << ") : ";
cin >>vtr[i][j];
}
}
write(); //Prints the array
}

The three matrixs will be construct when you define Matrix A, B, C. So the matrix size is 2x2. When you call function cin to assign value to some position is not in 2x2 will not work.

Related

Why the array is not sorted correctly?

the problem is
arange the columns of the array X (n, m) in ascending order.
I wrote such code in c ++ myself, but in the end it does not sort all the columns correctly. Please help if anyone knows.
#include <iostream>
using namespace std;
int main() {
int n, m;
cout << "array size: n = ";
cin >> n;
cout << "array size: m = ";
cin >> m;
int array[n][m];
int arrayS[n];
for (int z = 0; z < n; z++) {
for (int a = 0; a < m; a++) {
cin >> array[z][a];
}
}
for (int i = 0; i < n; i++) {
arrayS[i] = array[i][0];
}
for (int y = 0; y < n; y++) {
for (int i = 0; i < m; i++) {
cout << array[y][i] << " ";
}
cout << endl; //endline
}
cout << "************************************\n";
cout << "massivin sutunlari\n";
int enk = 0;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (arrayS[j] > arrayS[j + 1])
{
enk = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = enk;
}
}
for (int i = 0; i < n; i++)
{
cout << arrayS[i] << " ";
}
}
First of all, we need to make your code compilable. You are using so called VLA (variable length arrays), like in int array[n][m];. Rhese VLAs are not part of the C++ language and will not compile. I replaced them with a std::vector which will work in the same way. Then I corrected the code identations (I edited also your question) and then it is possible to compile.
It will then lool like the below (but of course still not working)
#include <iostream>
#include <vector>
int main() {
int n, m;
std::cout << "array size: n = ";
std::cin >> n;
std::cout << "array size: m = ";
std::cin >> m;
std::vector<std::vector<int>> array(n, std::vector<int>(m, 0));
std::vector<int> arrayS(n);
for (int z = 0; z < n; z++) {
for (int a = 0; a < m; a++) {
std::cin >> array[z][a];
}
}
for (int i = 0; i < n; i++) {
arrayS[i] = array[i][0];
}
for (int y = 0; y < n; y++) {
for (int i = 0; i < m; i++) {
std::cout << array[y][i] << " ";
}
std::cout << std::endl; //endline
}
std::cout << "************************************\n";
std::cout << "massivin sutunlari\n";
int enk = 0;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (arrayS[j] > arrayS[j + 1])
{
enk = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = enk;
}
}
for (int i = 0; i < n; i++)
{
std::cout << arrayS[i] << " ";
}
}
Some basic hints. Please use "speaking" variable names and write many many comments, best, one than more comment per line of code. Then you would already see the problems by yourself.
You have some hard bugs in your code that will most likely crash you program. Where you thy to sort, you use the magic number 9 (for whatever reasons) and so go out of bounds of the define arrays.
Additionally, your implementation of bubble sort is wrong. You may check many many examples in the net.
Then, you do only sort one column. You need to implement a bubble sort for each column of your matrix.
As a next step I will use better variable names and write comments. The code will still not work. But see and understand the difference.
#include <iostream>
#include <vector>
int main() {
// Here we will define the dimensions for our matrix
int numberOfRows{}, numberOfColumns{};
// Inform user what to do. Enter number of rows of the matrix
std::cout << "\nPlease enter the number of rows: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfRows;
// Inform user what to do. Enter number of columns of the matrix
std::cout << "\nPlease enter the number of columns: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfColumns;
// Define the array for the complete 2d matrix
std::vector<std::vector<int>> array(numberOfRows, std::vector<int>(numberOfColumns, 0));
// We can store one column here
std::vector<int> arrayS(numberOfRows);
// Inform user what to do. Enter all data for the matrix
std::cout << "\nPlease enter all data for the matrix";
// Now read all data, for all rows and columns from the user, via std::cin
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cin >> array[row][col];
}
}
// Copy the first column in a separate array
for (int i = 0; i < numberOfRows; i++) {
arrayS[i] = array[i][0];
}
// Show current data in our matrix
std::cout << "\n\nThe matrix:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
// SHow some status message
std::cout << "\n\n\n************************************\n";
std::cout << "Sorted first column\n";
// This is a temporary variable needed to swap 2 values
int tempValue = 0;
// Try to do bubble sort
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (arrayS[j] > arrayS[j + 1])
{
tempValue = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = tempValue;
}
}
// Show the result of the sorting
for (int i = 0; i < numberOfRows; i++)
{
std::cout << arrayS[i] << " ";
}
}
Next, we fix the sorting for one column.
Only minor changes needed:
#include <iostream>
#include <vector>
int main() {
// Here we will define the dimensions for our matrix
int numberOfRows{}, numberOfColumns{};
// Inform user what to do. Enter number of rows of the matrix
std::cout << "\nPlease enter the number of rows: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfRows;
// Inform user what to do. Enter number of columns of the matrix
std::cout << "\nPlease enter the number of columns: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfColumns;
// Define the array for the complete 2d matrix
std::vector<std::vector<int>> array(numberOfRows, std::vector<int>(numberOfColumns, 0));
// We can store one column here
std::vector<int> arrayS(numberOfRows);
// Inform user what to do. Enter all data for the matrix
std::cout << "\nPlease enter all data for the matrix\n";
// Now read all data, for all rows and columns from the user, via std::cin
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cin >> array[row][col];
}
}
// Copy the first column in a separate array
for (int i = 0; i < numberOfRows; i++) {
arrayS[i] = array[i][0];
}
// Show current data in our matrix
std::cout << "\n\nThe matrix:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
// SHow some status message
std::cout << "\n\n\n************************************\n";
std::cout << "Sorted first column\n";
// This is a temporary variable needed to swap 2 values
int tempValue = 0;
// Try to do bubble sort
// Go over all entries-1 in the column array.
// And compare the current value with the next value
for (int i = 0; i < numberOfRows-1; i++)
for (int j = 0; j < numberOfRows - 1; j++)
{
// If this value is bigger than the following value, then swap them
if (arrayS[j] > arrayS[j + 1])
{
// Swap
tempValue = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = tempValue;
}
}
// Show the result of the sorting
for (int i = 0; i < numberOfRows; i++)
{
std::cout << arrayS[i] << " ";
}
}
This works already. But, my gues is that all columns shall be sorted.
Then, finally, it would look like that:
#include <iostream>
#include <vector>
int main() {
// Here we will define the dimensions for our matrix
int numberOfRows{}, numberOfColumns{};
// Inform user what to do. Enter number of rows of the matrix
std::cout << "\nPlease enter the number of rows: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfRows;
// Inform user what to do. Enter number of columns of the matrix
std::cout << "\nPlease enter the number of columns: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfColumns;
// Define the array for the complete 2d matrix
std::vector<std::vector<int>> array(numberOfRows, std::vector<int>(numberOfColumns, 0));
// Inform user what to do. Enter all data for the matrix
std::cout << "\nPlease enter all data for the matrix\n";
// Now read all data, for all rows and columns from the user, via std::cin
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cin >> array[row][col];
}
}
// Show current data in our matrix
std::cout << "\n\nThe matrix:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
// SHow some status message
std::cout << "\n\n\n************************************\n";
std::cout << "Matrix with sorted column\n";
// This is a temporary variable needed to swap 2 values
int tempValue = 0;
// Try to do bubble sort
// Go over all entries-1 in the column array.
// And compare the current value with the next value
// Do for all columns
for (int col = 0; col < numberOfColumns; ++col)
for (int i = 0; i < numberOfRows-1; ++i)
for (int row = 0; row < numberOfRows - 1; ++row)
{
// If this value is bigger than the following value, then swap them
if (array[row][col] > array[row + 1][col])
{
// Swap
tempValue = array[row][col];
array[row][col] = array[row + 1][col];
array[row + 1][col] = tempValue;
}
}
// Show the result of the sorting
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
}

Add the Edges of 2D array and return its answer

What's wrong with my code
I Have to add all the edge values of the 2D Array.
The Function is not returning what I want. Its returning garbage value.
Program Req Output : Add all the edges value of the 2D Array and return its answer.
You are not allowed to use Vector etc.
Here is my Code :
#include <iostream>
using namespace std;
const int rows = 3;
const int cols = 4;
void AddEdges (int arr[rows][cols])
{
int sum = 0;
int totalOfEdges = 0;
int i,j;
int k = 0;
int l = 0;
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= cols; j++)
{
if (i == 1 || i == rows || j == 1 || j == cols)
{
sum = arr[k][l];
totalOfEdges = sum + totalOfEdges;
}
l++;
}
k++;
}
cout << "Total of Edges = " << totalOfEdges << endl;
}
int main()
{
int arr[3][4] = {0};
cout << "Enter Elements for Array = \n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
AddEdges(arr);
}
My Output :
Leaving the Correct Code in Case Any one need it .
#include <iostream>
using namespace std;
const int rows = 3;
const int cols = 4;
void AddEdges (int arr[rows][cols])
{
int sum = 0;
int totalOfEdges = 0;
int i,j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
if (i == 0 || i == (rows-1) || j == 0 || j == (cols-1))
{
sum = arr[i][j];
totalOfEdges = sum + totalOfEdges;
}
}
}
cout << "Total of Edges = " << totalOfEdges << endl;
}
int main()
{
int arr[3][4] = {0};
cout << "Enter Elements for Array = \n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
cout << "--------" << endl;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
AddEdges(arr);
}

C++ Laplace expansion

I'm writing a program to find the determinant of a matrix n x n, using Laplace expansion.
Briefly, the program creates a two-dimensional array based on a user request. The users choose the size of the two-dimensional array and fills it in themselves. Next comes the computation of the matrix using Laplace.
The problem is that I can't use the resulting array values in the determinant function. I'm completely new to C ++, so any help would be welcome. The code shown below. Thanks
#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;
void fin(int**, int, int);
void fout(int**, int, int);
int main() {
int **board, n;
double alpha, beta;
cout << "Enter the number of rows and columns: ";
cin >> n;
cout << endl;
board = new int* [n];
for(int row = 0; row < n; row++)
board[row] = new int[n];
fin(board,n,n);
cout << endl;
fout(board,n,n);
cout << endl;
cout << "Determinant of the matrix is " << determinant(board, n);
cout << endl;
return 0;
}
void fin(int **p, int R, int C)
{
for(int row = 0; row < R; row++)
{
cout << "Enter " << C + 1 << " numbers for row number " << R + 1 << ": ";
for(int col = 0; col < C; col++)
cin >> p[row][col];
cout << endl;
}
}
void fout(int **p, int R, int C)
{
for(int row = 0; row < R; row++)
{
for(int col = 0; col < C; col++)
cout << setw(5) << p[row][col];
cout << endl;
}
}
int determinant( int **result, int n) {
int det = 0;
int submatrix[10][10];
if (n == 2)
return ((result[0][0] * result[1][1]) - (result[1][0] * result[0][1]));
else {
for (int x = 0; x < n; x++) {
int subi = 0;
for (int i = 1; i < n; i++) {
int subj = 0;
for (int j = 0; j < n; j++) {
if (j == x)
continue;
submatrix[subi][subj] = result[i][j];
subj++;
}
subi++;
}
det = det + (pow(-1, x) * result[0][x] * determinant( submatrix, n - 1 ));
}
}
return det;
}

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 */

Dynamic Multidimensional array in C++

I made Matrix Multiplication program in c++ using dynamic Multidimensional arrays.
problem is when i enter test values
matrix A = row1{ 1 } , row2 { 2 } matrix B = row1 {1 ,2 , 3} , it stops working at the loop where user
inputs values of first array , i found it using debugging. but program works fine when i enter
matrix A = row1{ 1 , 2 } , row2 { 3 , 4 } matrix B = row1 {5 , 6 } , row2 {7 , 8}
i want this program to be a general program that can multiply all matrixs
#include <iostream>
using namespace std;
class Lab_02
{
public:
void Product(){
int a1Rows, a1Columns;
int a2Rows, a2Columns;
cout << "Plz Enter the no. of rows for Array 1 :";
cin >> a1Rows;
cout << "Plz Enter the no. of columns for Array 1 :";
cin >> a1Columns;
cout << "Plz Enter the no. of rows for Array 2 :";
cin >> a2Rows;
cout << "Plz Enter the no. of columns for Array 2 :";
cin >> a2Columns;
int **dynamicArray = 0;
int **dynamicArray2 = 0;
int **dynamicArray3 = 0;
cout << endl;
for (int i = 0; i < a1Rows; i++)
{
dynamicArray3 = new int *[a1Rows];
}
for (int i = 0; i < a2Columns; i++)
{
dynamicArray3[i] = new int[a2Columns];
}
// memory allocated for elements of rows.
for (int i = 0; i < a1Rows; i++)
{
dynamicArray = new int *[a1Rows];
}
// memory allocated for elements of each column.
for (int i = 0; i < a1Columns; i++)
{
dynamicArray[i] = new int[a1Columns];
}
// memory allocated for elements of rows.
for (int i = 0; i < a2Rows; i++)
{
dynamicArray2 = new int *[a2Rows];
}
// memory allocated for elements of each column.
for (int i = 0; i < a2Columns; i++)
{
dynamicArray2[i] = new int[a2Columns];
}
cout << "enter the values or array 1 \n";
for (int i = 0; i < a1Rows; i++)
{
for (int j = 0; j < a1Columns; j++)
{
cout << "array[" << i << "][" << j << "]\t";
cin >> dynamicArray[i][j];
}
}
cout << "enter the values or array 2 :\n";
for (int i = 0; i < a2Rows; i++)
{
for (int j = 0; j < a2Columns; j++)
{
cout << "array[" << i << "][" << j << "]\t";
cin >> dynamicArray2[i][j];
}
}
int sum;
for (int i = 0; i < a1Rows; i++)
{
for (int j = 0; j < a1Columns ; j++)
{
sum = 0;
for (int k = 0; k < a2Columns ; k++)
{
sum = sum + (dynamicArray[i][k] * dynamicArray2[k][j]);
}
dynamicArray3[i][j] = sum;
}
}
cout <<"Result" << endl << endl;
for (int i = 0; i < a1Rows; i++)
{
for (int j = 0; j < a2Columns; j++)
{
cout << dynamicArray3[i][j] << "\t";
}
cout << endl;
}
}
};
void main(void)
{
Lab_02 object;
object.Product();
}
Your memory allocations for the matricies are the issue.
Change them to something like the following
// memory allocated for elements of rows.
dynamicArray = new int *[a1Rows];
// memory allocated for elements of each column.
for (int i = 0; i < a1Rows; i++)
{
dynamicArray[i] = new int[a1Columns];
}
You need to allocate one array of array for the rows and then you need to loop over the rows and allocate the columns.
The issue with the code is that you are not supposed to allocate the "rows" in a loop. All you need is one allocation for the rows, and then loop to allocate the data for each row.
So for example, instead of this:
for (int i = 0; i < a1Rows; i++)
{
dynamicArray = new int *[a1Rows];
}
// memory allocated for elements of each column.
for (int i = 0; i < a1Columns; i++)
{
dynamicArray[i] = new int[a1Columns];
}
The correct way would be this:
dynamicArray = new int *[a1Rows];
for (int i = 0; i < a1Columns; i++)
{
dynamicArray[i] = new int[a1Columns];
}
You made the same mistake for each of the loops.
Also, some points:
You failed to deallocate the memory that was allocated.
If you used std::vector, then things become much easier.
You need to check if the matrices are multiplyable before performing the sum loop. By multiplyable meaning that the number of columns and rows of matrix A and B satisfy the requirements for multiplication of A and B.
for (int i = 0; i < a1Rows; i++)
{
for (int j = 0; j < a1Columns; j++)
{
sum = 0;
for (int k = 0; k < a2Columns; k++)
sum = sum + (dynamicArray[i][k] * dynamicArray2[k][j]);
dynamicArray3[i][j] = sum;
}
}
This loop will go haywire if the dynamicArray1 and dynamicArray2 do not have the requisite number of columns and rows before multiplying.
First, the following test should be done before multiplying:
if (a1Columns != a2Rows)
return;
Second, your k loop is wrong. It should be this:
for (int k = 0; k < a2Rows; k++)
sum = sum + (dynamicArray[i][k] * dynamicArray2[k][j]);
dynamicArray3[i][j] = sum;