I am learning C++ by myself,by solving different problems.
I am trying to solve problem which was originally designed for Pascal in C++.
It should ask user to input 3 integers M,N and q.
Then it should make 2d array of integers with size MxN, where all the elements of (I=I,...M) line will be the members of geometrical progression with first element equal to number of line (I) and denominator q.
I wanted to create a dynamic massive, but I realized that it won't really work with two undefined integers. So, I tried vectors. I guess that I created them in a right way, but I've got no idea how to make a geometrical progression.
Here is my code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int m, n, q;
cout << "Enter the number for M \n";
cin >> m;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "This is not a number! " << endl;
system("pause");
return 0;
}
cout << "Enter the number for N \n";
cin >> n;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "This is not a number! " << endl;
system("pause");
return 0;
}
cout << "Enter the number for Q \n";
cin >> q;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "This is not a number! " << endl;
system("pause");
return 0;
}
int** matrix;
matrix = new int*[m];
for (int i = 0; i < m; i++)
matrix[i] = new int[n];
for (int i = 0; i < m; i++)
{
matrix[i][0] = i + 1;
}
for (int i = 0; i < m; i++)
{
for (int j = 1; j < n; j++)
{
matrix[i][j] = (i + 1)*pow(i, j);
cout << matrix[i][j];
}
}
system("pause");
return 0;
}
Note: You can create a two dimensional array of a variable size, although it involves memory allocation and is slightly ugly.
int** matrix;
matrix = new int*[M];
for (int i = 0; i < M; i++)
matrix[i] = new int[N];
That's the code to create an array of size MxN.
Don't forget to deallocate your memory like so:
for (int i = 0; i < M; i++)
delete matrix[i];
delete matrix;
As far as your question about the geometric progression, I am unsure of what you are asking. When you say geometric progression do you refer to something along the lines of 2 10 50 250 etc.? I am not sure what you mean by "lines" as you don't refer to any such variable in your code.
EDIT
So once the MxN matrix is created, iterate through the rows and initialize the rows like so:
for (int i = 0; i < M; i++)
{
matrix[i][0] = i+1;
}
This should set the first column of each row to the correct number.
Then something along the lines of this should fill out the rest of the geometric progression:
for (int i = 0; i < M; i++)
{
for (int j = 1; j < N; j++)
{
matrix[i][j] = (i+1)*pow(r,j);
//note that you'll probably have to do some typecasting
//p.s. I'm not 100% sure that this is the correct formula
}
}
I think this is what you are looking for. Let me know if it works because I haven't tested it myself.
Print the matrix like this:
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
Related
I have been trying to debug this code for awhile, but I'm not sure how to actually access values in my IDE when they are located in dynamically allocated memory. This program is supposed to initialize two matrices based on the user's input and then multiply them together, if possible.
I have found a few mistakes and corrected them, but I'm not sure what is causing this issue.
#include <iostream>
using namespace std;
typedef int* IntArrayPtr;
int main() {
int r1, c1, r2, c2;
do {
//GET DIMENSIONS OF MATRICIES
cout << "Welcome! This program takes two matricies and multiplies them together.\n"
<< "Enter the number of rows and number of columns for Matrix 1: ";
cin >> r1 >> c1;
cout << "Enter the number of rows and number of columns for Matrix 2: ";
cin >> r2 >> c2;
//DETECT IF MULTIPLICATION CAN HAPPEN
if (r1 != c2) {
cout << "Error: matricies cannot be multiplied. Please enter a new set.\n";
}
} while (r1 != c2); //have the user enter again if the rows and columns don't match
cout << endl;
//INTIALIZE MATRICIES USING DYNAMIC ARRAYS
//intialize MATRIX 1
IntArrayPtr *a = new IntArrayPtr[r1];
cout << "For MATRIX 1: Enter the contained values. Press enter after each entry.\n";
for (int i = 0; i < r1; i++) {
a[i] = new int[c1]; //init columns for each row
cout << "ROW" << i + 1 << "\n";
for (int j = 0; j < c1; j++) {
cin >> a[i][j]; //fill columns of rows
}
cout << endl;
}
//intialize MATRIX 2
IntArrayPtr *b = new IntArrayPtr[r2]; //init rows
cout << "For MATRIX 2: Enter the contained values. Press enter after each entry.\n";
for (int i = 0; i < r2; i++) {
b[i] = new int[c2]; //intialize columns
cout << "ROW" << i + 1 << "\n";
for (int j = 0; j < c2; j++) {
cin >> b[i][j]; //fill columns of rows
}
cout << endl;
}
//INITIALIZE MATRIX TO STORE RESULT IN
//matrix will have the rows of the first and columns of the second, according to matrix multiplication
IntArrayPtr *c = new IntArrayPtr[r1]; //init rows
for (int i = 0; i < r1; i++) {
c[i] = new int[c2]; //init columns
}
//MULTIPLY MATRICIES
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
for (int k = 0; k < c1; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
//PRINT RESULT
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
cout << c[i][j] << " ";
}
cout << endl;
}
delete[] a; delete[] b; delete[] c;
system("pause");
return 0;
}
The matrix should be the result of multiplication, but when I try to execute the program using small matricies (e.g. 3 x 2 times 2 x 3), the output spits out what seems to me to be garbage. I'm sure my mistake is silly, but help would be appreciated.
You didn't initialize the matrix c properly. Try this
//INITIALIZE MATRIX TO STORE RESULT IN
//matrix will have the rows of the first and columns of the second, according to matrix multiplication
IntArrayPtr *c = new IntArrayPtr[r1]; //init rows
for (int i = 0; i < r1; i++) {
c[i] = new int[c2]; //init columns
for (int j = 0; j < c2; j++) {
c[i][j] = 0;
}
}
I'm in the early stages of my program and right now I'm simply trying to initialize a 2D array to hold all dashes but I keep getting a ECX_BAD_ACCESS error. My code seems to work with a square array (ex: 5x5 or 6x6) but if I do 10 by 5 I get the error.
void readMatrix(char **twoDarray, int &rows, int &cols)
{
std::cout << "Enter number of rows for board";
std::cin >> rows;
std::cout << "Enter number of columns for board";
std::cin >> cols;
//dynamic 2D array initialization
twoDarray = new char*[rows];
for(int i = 0; i < cols; ++i)
twoDarray[i] = new char[rows];
//set elements of array to dashes
for(int i = 0; i < rows; ++i)
for(int j = 0; j < cols; ++j){
twoDarray[i][j] = '-';
}
//printing the array
for(int i = 0; i < rows; ++i){
std::cout << " " << std::endl;
for(int j = 0; j < cols; ++j)
std::cout << twoDarray[i][j] << " ";
}
}
Your first for-loop should go from 0 to #rows, not #cols. Also, in the body of that same loop allocate cols, not rows.
I am trying to create MxN matrix using 2D-arrays in C++.
The createMatrix() function asks for user input for matrix items and the printMatrix() function has to print the matrix.
But the printing task is not working (I can't access the array created, I don't understand why)
I receive the error :
matrix.cpp:35:20: error: invalid types ‘int[int]’ for array subscript
cout << matrix[i][j];
The code I'm working with is:
#include "iostream"
using namespace std;
// user input matrix
int createMatrix(int m, int n){
int arr[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << "A[" << i << "][" << j << "] : ";
cin >> arr[i][j];
}
cout << endl;
}
return arr[m][n];
}
/*
void printMatrix(int matrix[][2], int m, int n){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << matrix[i][j];
}
}
}
*/
int main(){
int m = 2, n = 2; // m = rows, n = columns
int matrix = createMatrix(m,n);
// printMatrix(matrix, m, n); // not working as sub-routine too, main target to make it work with sub-routine
// to print matrix
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << matrix[i][j];
}
}
return 0;
}
matrix is an int not an int[][]. Since it is an int there is no subscript operator and that is why you are getting the error you are getting. You are also using veriable length arrays which is not standard C++. I would suggest you change your code to use a std::vector like
std::vector<std::vector<int>> createMatrix(int m, int n)
{
std::vector<std::vector<int>> arr(m, std::vector<int>(n));
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << "A[" << i << "][" << j << "] : ";
cin >> arr[i][j];
}
cout << endl;
}
return arr;
}
And then main() would be:
int main(){
int m = 2, n = 2; // m = rows, n = columns
std::vector<std::vector<int>> matrix = createMatrix(m,n);
// printMatrix(matrix, m, n); // not working as sub-routine too, main target to make it work with sub-routine
// to print matrix
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cout << matrix[i][j];
}
}
return 0;
}
Your matrix is not array. it is int.
You need to work with the pointers.
Yes, createMatrix works but you won't be able to do anything with what it created. Because:
arr[n][m] is local (and out of boundaries by the way). It is not a matrix as you probably thought but an item of arr at position [n][m].
It is not well defined to declare array of fixed sizes with vary sizes that depend on function input.
You need to pass to createMatrix array from the main() as pointer (like you did in printMatrix) and createMatrix should work with it and not something local.
Now regarding your original question:
But the printing task is not working (I can't access the array
created, I don't understand why)
matrix was defined as int, not as array.
int matrix = createMatrix(m,n);
first off sorry for the slightly messy code as I was fiddling with different things to try to get it to work. As of now, my code can multiply Square Matrices just fine; however, it has difficulties computing Non Square Matrices. My best guess after debugging is how i re-size my vectors, and that there is an out of bounds error which causes the program to crash. Any help would be appreciated, my code should be able to Multiply any Vectors sizes withing Matrix Multiplication Rules.
I also would like to note this is a HW assignment so I am limited to how I can build my code, basically ONLY using vectors, cannot write your own class etc....
#include <iostream>
#include <vector>
using namespace std;
void multiply_matrices(vector <vector<int> > matrix1,vector <vector<int> > matrix2, int cols, int rows2);
void setMatrix(vector <vector<int> > &matrix, int rows, int cols);
int main()
{
int rows, cols, rows2, cols2;
vector< vector<int> > matrix, matrix2;
cout<<"Please enter the number of Rows and Columns for your first Matrix."<<endl;
cout<<"Rows: ";
cin>>rows;
cout<<"Columns: ";
cin>>cols;
matrix.resize(cols, vector<int>(rows,0)); //Saw this online so not sure how it works but it works, if i take out one i cant do row<column and vice versa
matrix.resize(rows, vector<int>(cols,0));
cout<<"Size has been declared, please enter data for your matrix"<<endl;
setMatrix(matrix,rows,cols);
cout<<"Second Matrix Automatically Set by Matrix Multiplication Rule"<<endl; //Just automatically sets second matrix as per Matrix Multiplication Rule
rows2=cols;
cols2=rows;
cout<<"Second Matrix Size is: " << rows2 << " by " << cols2 << endl;
matrix2.resize(cols2, vector<int>(rows2,0));
matrix2.resize(rows2, vector<int>(cols2,0));
setMatrix(matrix2,rows2,cols2);
cout<<"Multiplied Matrix is:"<<endl;
multiply_matrices(matrix,matrix2,cols,rows2);
system("PAUSE");
return 0;
}
void setMatrix(vector <vector<int> > &matrix, int rows,int cols){
int num;
for(int i = 0; i < rows; i ++)
{
for (int j = 0; j < cols; j++)
{
cout << "Enter Value for Row " << (i+1) << " Column " << (j+1) << ": ";
cin>>num;
matrix[i][j]=num;
}
cout << endl;
}
/*for(int i = 0; i < rows; i ++)
{
for (int j = 0; j < cols; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
*/
}
void multiply_matrices(vector <vector<int> > matrix1,vector <vector<int> > matrix2, int cols, int rows2){
vector< vector<int> > tempMatrix;
int newrows=rows2;
int newcols=cols;
int sum;
tempMatrix.resize(newcols, vector<int>(newrows,0)); //Resizing new matrix to proper size, so if it was (2x3)(3x2), new matrix is (3x3)
for (int i = 0; i < newrows; i++) //This Works Fine for Square Matrixes but not for others, i have no clue how to fix it?
{
for (int j = 0; j < newcols; j++){
//sum=0;
for (int u = 0; u < newcols; u++)
{
//sum+=matrix1[i][u] * matrix2[u][j];
//tempMatrix[i][j]=sum;
tempMatrix[i][j] += matrix1[i][u] * matrix2[u][j];
}
}
}
for(int i = 0; i < newrows; i ++)
{
for (int j = 0; j < newcols; j++)
{
cout << tempMatrix[i][j] << " ";
}
cout << endl;
}
}
Initialize your first matrix like this:
matrix.resize(rows, vector<int>(cols,0));
and your second like this:
matrix2.resize(rows2, vector<int>(cols2,0));
where rows2 = cols. Note that there is no "multiplication rule" that implies cols2 == rows.
The problem is in your multiply_matrices function where the loops should be
for (int i = 0; i < rows; i++) // or matrix1.size()
for (int j = 0; j < cols2; j++) // or tempMatrix[i].size()
for (int u = 0; u < cols; u++) // or rows2 or matrix1[i].size()
but as already stated in the comments, it would be better to use vector::size() instead of passing the sizes as additional parameters.
Also, if you multiply (2x3)(3x2), the result is (2x2):
tempMatrix.resize(rows, vector<int>(cols2,0));
There is nothing wrong with the resize() function. What may be wrong is that you ignore the maximum size and rely solely on variables that are passed to your functions.
For example, your setMatrix function is passed rows and cols, but this is not necessary.
The function should be rewritten using only the matrix to provide the sizes to the loops:
void setMatrix(vector<vector<int> > &matrix)
{
int num;
for(int i = 0; i < matrix.size(); ++i)
{
for (int j = 0; j < matrix[i].size(); ++j)
{
cout << "Enter Value for Row " << (i+1) << " Column " << (j+1) << ": ";
cin>>num;
matrix[i][j] = num;
}
cout << endl;
}
}
You have the same issue with multiply_matrix. What you should be doing is ensure that you're loops use the return value of vector::size(), which you do not do. The problem is here:
for (int i = 0; i < newrows; i++)
{
for (int j = 0; j < newcols; j++)
{
for (int u = 0; u < newcols; u++)
{
tempMatrix[i][j] += matrix1[i][u] * matrix2[u][j];
You sized the tempMatrix to newrows rows and newcols columns. But how do you know that matrix1 and matrix2 have at least newrows rows and newcols columns? You don't know, but you just assume they do.
So you either need to ensure that the size of matrix1 and matrix2 can accommodate the number of rows/columns, or you throttle those loops to use the minimum rows/columns.
Overall, the issue is that nowhere do you use vector::size() in your code that I see. So start to use size() to your advantage -- don't create superfluous (and possibly erroneously set) variables that supposedly denote the sizes of the rows and columns.
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;