Reputation: 162
I'm writing a program to populate two multidimensional arrays and multiply their elements using for loops only. The code's pretty simple yet I'm stuck with a host of errors from the multiplication loop. I can't wrap my head around this one.
Is there a problem with my loop syntax? I'll attach the code below. Lines 48 and 49 are the loop code for multiplication. Thanks in advance.
#include <iostream>
#include <iostream>
using namespace std;
int main()
{
cout << "Creating array: " << endl;
cout << " " << endl;
cout << "Please enter the number of rows: ";
int numRows2 = 0;
cin >> numRows2;
cout << " " << endl;
cout << "Please enter the number of columns: ";
int numCols2 = 0;
cin >> numCols2;
double myNums2[numRows2][numCols2];
for (int counter = 0; counter < numRows2; counter++)
{
for (int counter_a = 0; counter_a < numCols2; counter_a++)
{
cout << "Enter Element [" << counter << "][" << counter_a << "]: ";
cin >> myNums2[counter][counter_a];
}
}
cout << " " << endl;
cout << "Displaying contents of the array: " << endl;
for (int counter = 0; counter < numRows2; ++counter)
{
for (int counter_a = 0; counter_a < numCols2; ++counter_a)
cout << "Element [" << counter <<"][" << counter_a << "]: " << myNums2[counter][counter_a] << endl;
}
cout << " " << endl;
cout << "Multiplying each element in myNums1 by each element in myNums2: " << endl;
for (int indexRow1 = 0, int indexCol1 = 0; indexRow1 < numRows, indexCol1 < numCols; ++indexRow1, ++indexCol1)
for (int indexRow2 = 0, int indexCol2; indexRow2 < numRows2, indexCol2 < numCols2; ++indexRow2, ++indexCol2)
{
cout << myNums1[indexRow1][indexRow2] << " x " << myNums2[indexRow2][indexCol2] << " = " << myNums1[indexRow1][indexCol1] * myNums2[indexRow2][indexCol2] << endl;
}
return 0;
}
Upvotes: 0
Views: 400
Reputation: 793
There are two errors in your code at the for
loops:
for (int indexRow1 = 0, int indexCol1 = 0; indexRow1 < numRows, indexCol1 < numCols; ++indexRow1, ++indexCol1)
for (int indexRow2 = 0, int indexCol2; indexRow2 < numRows2, indexCol2 < numCols2; ++indexRow2, ++indexCol2)
for (int indexRow1 = 0, int indexCol1 = 0, ...)
The correct one is:
for (int indexRow1 = 0, indexCol1 = 0, ...)
numRows
and numCols
before the for
loop. You may need to check your code and declare them.Upvotes: 1
Reputation: 1533
You can not declare two variables in the for
loop as you are doing it.
You can check this thread for ways to achieve it.
On the snippet you share, certain variables are not declared, numRows
, numCols
, myNums1
.
indexCols2
is not initialized, even though the for loop is not correct as it is.
As @cigien mentioned in the comment, to use an array you will have to allocate memory dynamically if you want to read the size from the user.
Upvotes: 1