Multiplying elements in 2d array - c++

I'm having a problem with the last row of my program. I can't figure out how to multiply the last row by the first row in my program. The multiplication table
works by multiplying the first row by the second, second by third, and so on.
int main() {
int temp;
const int row = 10;
const int col = 5;
int arr[row][col];
int arr2[10][5];
srand(((unsigned)time(0)));
cout << "Original" << endl;
for (int i = 0; i<10; i++) {
for (int j = 0; j<5; j++) {
temp = 1 + rand() % 99;
arr[i][j] = temp;
int arr2 = arr[i][j];
cout << setw(4) << arr2<< setw(5) << " | ";
}
cout << endl;
}
cout << "\n\nMultiplied rows" << endl;
for (int i = 0; i<row; i++) {
for (int j = 0; j < col; j++) {
if (i < 9)
arr[i][j] *= arr[i + 1][j];
else if (i == 9)
cout << setw(4) << arr[i][j]<< setw(5) << " | ";
}
cout << endl;
}
return 0;
}
(it's the last else statement I'm having a problem with)
i tried arr[i][j]=arr[1][i]*arr[9][j]
but that didn't work

First, the answer to your question.
You cant really multiply the last row with the first one because you overwrote it already when arr[i][j] *= arr[i + 1][j]; line executed for i = 0 and j = 0 to 9
The naive solution would be to either store the multiplied numbers in a new array, or don't overwrite the old array and just print the computed values.
Even with that, you will have to make other fixes but I am not really going to do your homework for you.
Just FYI, if you are handing this to an instructor they will call out a number of issues, like the fact that you have const int row and col defined but you only use them once .You should just use those variables; so instead of typing things like 10 , 5 and 9 you should type row, col , row -1.
Also the first arr2 variable is unused and the one in the loop could just as easily not be there and your code would be cout << setw(4) << arr[i][j]<< setw(5) << " | ";
I could go on but I will leave you to find the rest...
Good luck.

Related

C++ [Error] invalid conversion from 'int' to 'int (*)[2]' [-fpermissive] [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am a beginner and I keep getting an error when I am calling my function. I am trying to get the user to input a value for the array and then get it to display it in a table format. Also, I am trying to display a 3x3 matrix in the end.
void DMMatrix(int DM[2][2]){
int number;
cout << "Input 0's and 1's to the DM[2][2]\n\n";
for (int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cout << "DM[" << i << "]"<< "[" << j << "]: ";
cin >> number;
DM[i][j] = number;
}
}
}
int main(){
int i, j, sum = 0;
int DM[2][2];
DMMatrix(DM[2][2]);
cout << "\n\nOutput (table format)\n\n";
for(i = 0;i < 3;i++){
for(j = 0;j < 3;j++){
cout << " " << DM[i][j] << " ";
}
cout << "\n";
}
sum = DM[0][0] + DM[0][1] + DM[0][2] + DM[1][0] + DM[1][1] + DM[1][2] + DM[2][0] + DM[2][1] + DM[2][2];
if (sum % 2 == 0){
cout << "\nSum is " << sum;
}
}
There are 3 problems in your program.
Mistake 1
You are calling the function DMMatrix incorrectly. The correct way to call DMMatrix would be:
DMMatrix(DM);//CORRECT WAY OF CALLING DMMatrix
Mistake 2
Your 2D array DM has 2 rows and 2 columns and you're accessing 3rd row and 3rd column of the array DM. But since the 3rd row and 3rd column doesn't exist, you have undefined behavior in your program. To solve this you can create a 3x3 2D array as shown below:
#include <iostream>
using namespace std;
void DMMatrix(int DM[3][3]){//2 CHANGED TO 3
int number;
cout << "Input 0's and 1's to the DM[2][2]\n\n";
for (int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
cout << "DM[" << i << "]"<< "[" << j << "]: ";
cin >> number;
DM[i][j] = number;
}
}
}
int main(){
int i, j, sum = 0;
int DM[3][3]; //2 CHANGED TO 3
DMMatrix(DM);
cout << "\n\nOutput (table format)\n\n";
for(i = 0;i < 3;i++){
for(j = 0;j < 3;j++){
cout << " " << DM[i][j] << " ";
sum += DM[i][j];//CALCULATE SUM HERE
}
cout << "\n";
}
cout << "\nSum is " << sum;
}
Mistake 3
You don't need to calculate the sum by writing each element of the array explicitly. You can calculate the sum inside the for loop in my modified above program. Also note that in your original code, while calculating the sum you were going out of bounds which leads to undefined behavior. The above shown program corrected this.
First, the size of the array that you have given to DM is 2x2 but your loop runs for 9 times considering the loop runs for 0, 1 and 2 which will cause a stack smash or Segmentation Fault
#include <iostream>
using namespace std;
void DMMatrix (int DM[3][3])
{
int number;
cout << "Input 0's and 1's to the DM[2][2]\n\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << "DM[" << i << "]" << "[" << j << "]: ";
cin >> number;
DM[i][j] = number;
}
}
}
int main ()
{
int i, j, sum = 0;
int DM[3][3];
DMMatrix (DM);
cout << "\n\nOutput (table format)\n\n";
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
cout << " " << DM[i][j] << " ";
}
cout << "\n";
}
sum = DM[0][0] + DM[0][1] + DM[0][2] + DM[1][0] + DM[1][1] + DM[1][2] +
DM[2][0] + DM[2][1] + DM[2][2];
if (sum % 2 == 0)
{
cout << "\nSum is " << sum;
}
}

C++ matrix problem : incorrect output for transpose matrix

I have to write a program to allow a user to input the number of rows and the number of columns of a matrix. The program will then construct the transpose of the matrix and display the transpose to the user, it is also supposed to display the trace and determinant of the matrix. I am having a problem with the output for the transpose, whenever the matrix is not a perfect square I get random numbers.
This is my code:
int main()
{
int matrix[10][10];
int row, column, i, j;
int temp = 0;
//size of matrix
cout << "Enter number of rows: ";
cin >> row;
cout << "Enter number of columns: ";
cin >> column;
// read the matrix values ( original matrix )
cout << "Enter the elements: \n";
for (i = 0; i < row; i++)
for (j = 0; j < column; j++)
cin >> matrix[i][j];
cout << "Matrix: \n";
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
cout << matrix[i][j] << ' ';
cout << endl;
}
// transpose the matrix values ( the matrix transposed )
cout << "Transpose of a Matrix: \n";
for (j = 0; j < row; j++)
{
for (i = 0; i < column; i++)
cout << matrix[i][j] << ' ';
cout << endl;
}
// trace of a matrix
int trace = 0;
if (row == column)
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
trace += matrix[i][i];
cout << "Trace of a Matrix: \n";
cout << trace << endl;
}
else
{
cout << "The trace will not be computed \n"
<< "The given matrix is not a perfect square" << endl;
}
// determinant of Matrix
int det = 0;
if (row == 2 && column == 2)
{
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
for (i = 0; i < row; i++)
cout << "Determinant of the Matrix: \n";
det = ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
cout << det << endl;
}
}
else
{
cout << "The determinant will not be computed \n"
<< "The given matrix is not a square" << endl;
}
return 0;
}
If I were to enter 3 rows and 2 columns and random elements my output looks like this:
Enter number of rows: 3
Enter number of columns : 2
Enter the elements:
1 5 6 -4 2 3
Matrix:
1 5
6 -4
2 3
Transpose of a Matrix:
1 6
5 -4
-858993460 -858993460
The trace will not be computed
The given matrix is not a perfect square
The determinant will not be computed
The given matrix is not a square
Is there something wrong in my code that causes -858993460 and -858993460 to come up?
Try this when printing the transpose (note the upper bounds for the loops have been swapped compared to your code) :
for (j = 0; j < column; j++)
{
for (i = 0; i < row; i++)
cout << matrix[i][j] << ' ';
cout << endl;
}
The reason you got "random elements", is because your code was reading and printing the contents of memory that hadn't been initialized yet.
Eg. in your example output, the first value -858993460 was obtained from matrix[2][0] (with j == 2 and i == 0), but that slot hadn't been filled with anything (the original matrix only occupies 0 <= i <= 2 and 0 <= j <= 1). Similarly, the second value -858993460 was obtained from matrix[2][1].
You are accessing parts of the memory, that have not been written to while reading in the matrix elements.
Instead of changing what i and j represent when printing the matrix, just change the order of the for loops from the order in that you were reading the elements.
cout << "Transpose of a Matrix: \n";
for (j = 0; j < column; j++)
{
for (i = 0; i < row; i++)
cout << matrix[i][j] << ' ';
cout << endl;
}

Difference of 2 sets retained in arrays - C++

Consider two sets retained in two arrays. Find the union, intersection and difference (relative complement) of the two sets.
I managed to solve the union and the intersection, but the difference is giving me a hard time. Any hints? And if possible, keep it as simple as possible, without functions or more complex aspects, because I'm a beginner and I still have a lot to learn.
Thank you in advance!
#include <iostream>
using namespace std;
int main()
{
int v1[100], v2[100], u[200], intersection[100], d[100];
unsigned int v1_length, v2_length, i, j, OK = 0, union_length;
cout << "Enter the number of elements of the first array:" << " ";
cin >> v1_length;
cout << "Enter the elements of the first array:" << '\n';
for (i = 0; i < v1_length; i++)
cin >> v1[i];
cout << "Enter the number of elements of the second array:" << " ";
cin >> v2_length;
cout << "Enter the elements of the second array:" << '\n';
for (i = 0; i < v2_length; i++)
cin >> v2[i];
//Union
union_length = v1_length;
for (i = 0; i < v1_length; i++)
u[i] = v1[i];
for (i = 0; i < v2_length; i++)
{
int ok = 0;
for (j = 0; !ok && j < v1_length; j++)
if (v1[j] == v2[i])
ok = 1;
if (!ok)
{
u[union_length] = v2[i];
union_length++;
}
}
cout << "The union of the two sets contained in the arrays is: ";
for (i = 0; i < union_length; i++)
cout << u[i] << " ";
cout << '\n';
//Intersection
unsigned int k = 0;
cout << "The intersection of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++)
if (v1[i] == v2[j])
{
intersection[k] = v1[i];
k++;
}
for (i = 0; i < k; i++)
cout << intersection[i] << " ";
cout << '\n';
//Difference
unsigned int l = 0, OK2 = 0;
cout << "The difference of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
{
for (j = 0; j < v2_length; j++)
{
if (v1[i] == v2[j])
OK2 = 1;
if (!OK2)
{
d[l] = v1[i];
l++;
}
}
}
for (i = 0; i < l; i++)
cout << d[i] << " ";
cout << '\n';
return 0;
}
It seems that the intersection is the best place to start. You want the items that only in appear in one of the two arrays, right?
So, for the inner loop, you need to compare all the elements. Then, if no match was found, you have the a unique element.
You need to add the curly braces {} to the for loop. I know that curly braces are distracting at times, but over time, you will probably find it safer to almost always include them to avoid confusion.
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++) {
if (v1[i] == v2[j]){
break; // this item is not unique
} else if(j == v2_length - 1){
d[l] = v1[i]; // This is the unique one, add it to the answer array
l++;
}
}
for (i = 0; i < l; i++)
cout << intersection[l] << " ";
cout << '\n';
You're on the right track!
You're doing a few things wrong. Here are some fixes you can try:
Only set OK2 to 0 once per inner-loop
Reset OK2 to 0 at the end of the inner-loop
Only do the insertion into d after the inner-loop has completed
As an optimization, consider breaking after you set OK2 to 1, as you know at that point it can never be set to 0 for the current value pointed to by the outer-loop.

Lesser number of columns of the second row "cuts off" a bigger number of columns of the first row

*Edit: Still, when input 3 columns for the 1st row and 2 columns for the 2th, in the output 1st row becomes 2-elemented as the first.
Problem with outputting dynamically allocated number of equipes with separately dynamically allocated number of columns (for number of catches for the each equip)... Namely, if I try to allocate 2 equipes and then for the first equip two "catches" of fish (two columns) and for second equip three catches of fish, everything is o.k.... but if I try input of smaller number of columns ("catches") for the second row (equip) then in the output the "excess" of the first row is "cutted off", so for example if there where a 3 columns input for the 1st row and 2 columns input for the second row, in the output there will be just two columns (indices of numbers) for the every of the two rows.
#include<iostream>
int main()
{
using namespace std;
int *sum;
int *a = new int;
int *b = new int;
cout << "Total number of equips: ";
cin >> *a;
// Allocate a two-dimensional 3x2 array of ints
int** ippArray = new int*[*a];
for (int i = 0; i < *a+1; ++i) {
ippArray[i] = new int[*b];
}
// fill the array
for (int i = 1; i < *a+1; ++i) {
cout << "Total number of catches for " << i << "th equip : ";
cin >> *b;
cout << "Equip number: " << i << endl;
for (int j = 1; j < *b+1; ++j) {
cout << "Catch number: " << j << endl;
cin >> ippArray[i][j];
ippArray[i][j];
}
}
// Output the array
for (int i = 1; i < *a+1; ++i) {
for (int j = 1; j < *b+1; ++j) {
cout << ippArray[i][j] << " ";
*sum = *sum + ippArray[i][j];
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << *sum-3;
// Deallocate
for (int i = 1; i < *a+1; ++i) {
delete [] ippArray[i];
}
delete [] ippArray;
// Keep the window open
cin.get();
return 0;
}
First, don't make your integers into pointers (int *a = new int;) unless they really need to be. It makes the code much harder to read, and if anyone has to maintain your code they'll call you an a-hole.
Second, int** ippArray = new int*[*a]; combined with multiple spots where you do this... for (int i = 1; i < *a+1; ++i) are bad. ippArray has valid references from 0 to *a, therefore it should be for (int i = 0; i < *a; ++i)
Edit: Try something like this http://ideone.com/4egQl3
Edit2: Also the standard advice...
{
std::vector<string> advice;
advice.push_back( "These will make your life easier" );
}
// No de-allocation needed!
Parts of your program that have undefined behaviour
Use of *b before you assign to it
Access out-of-bounds elements of all your arrays
Never initialise sum
Use of *sum before you assign to it
cleaned up, your code becomes
int main()
{
using namespace std;
int sum, a, b;
cout << "Total number of equips: ";
cin >> a;
typedef vector<vector<int> > vvint;
typedef vector<int> vint;
// Allocate a two-dimensional structure of ints
vvint ippArray(a);
// fill the array
for (vvint::size_t i = 0; i < a; ++i) {
cout << "Total number of catches for " << i+1 << "th equip : ";
cin >> b;
cout << "Equip number: " << i+1 << endl;
ippArray[i] = vint(b);
for (int j = 0; j < b; ++j) {
cout << "Catch number: " << j+1 << endl;
cin >> ippArray[i][j];
}
}
// Output the array
for (const vint & inner : ippArray) {
for (int num : inner) {
cout << num << " ";
sum += num;
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << sum;
cin.get();
return 0;
}

Arrays messed up C++

const int N = 5;
int person[] = {2, 3, 12, 5, 19};
int big = 0;
int small = 100;
int i;
for (i = 0; i <= N; i++)
{
cout << "Person[" << i << "] ate: " << person[i] << endl;
//cin >> person[i];
for (int j = i+1; j <= N; j++)
{
if (person[i] < person[j])
{
int tmp = person[i];
person[i] = person[j];
person[j] = tmp;
}
}
if (person[i]>big)
big=person[i];
if (person[i]<small)
small=person[i];
}
cout << "Person[" << i << "] ate the most pancakes: " << big << endl;
cout << "Person[" << i << "] ate the least pancakes: " << small << endl;
cout << "Sorted:" << endl;
for (i = 0; i < N; i++)
{
cout << "Person[" << i << "]: " << person[i] << endl;
}
system("pause");
output
Where I messed up those arrays it keeps showing me 2 but the bubble sorting works. And the other question is how to get the array index from the smallest value and the array index from the highest value?
In C++ arrays are ZERO 0 indexed. So you should change your for loops like this:
for (i = 0; i < N; i++)
^^^
{
// some code...
for (int j = i+1; j < N; j++)
^^^
{
// some code...
Because:
index -> 0 1 2 3 4
person[] = {2, 3, 12, 5, 19};
In your code the value of i and j will increment up to N which is 5. That means you are trying to access the array named person's 5th index which will create array index out of bound error.
Array indexing starts from zero so if there are N elements, last element will be at N-1 index.Accessing element at index N is going out of bounds.
for (i = 0; i <= N; i++)//should run till `N-1`
^^^
for (int j = i+1; j <= N; j++)//should run till `N-1`
^^^
If you want index of the highest and the lowest element,since you have sorted the array,the smallest values's index would be 0 and highest value's index will be N-1(opposite in your case because you have sorted the array in decreasing order)