Reputation:
having a trouble with a condition which tells if an element of a multidimensional array
as example arr[row][col] is exactly arr[col][row] then automatically assign the value of arr[col][row] to the same value of arr[row][col] without letting user enter it manually
That should be an example of the output
example[4][4] =
{
// 0 1 2 3
{ 0, 10, 15, 18}, // 0
{ 10, 0, 20, 14}, // 1
{ 15, 20, 0, 90}, // 2
{ 18, 14,90, 0}, // 3
here's my code
` int size;
int arr[size][size];
cout<<"Choose size of your multidimensional array [matrix]: ",cin>>size;
cout<<"Now enter your data [Respectively] \n";
for(int d=0 ; d<size ; d++)
{
for(int j=0; j<size; j++)
{
if (d==j)
{
arr[d][j]=0 ;
}
else if(arr[d][j]!=0 ) //there should be the problem
{
arr[j][d]=arr[d][j];
}
else
{
cin>>arr[d][j]; // Filling matrix
}
}
} `
Upvotes: 2
Views: 1324
Reputation: 1504
Here is a Minimum Working Example (MWE) that should solve your issues:
#include <iostream>
using namespace std;
int main()
{
cout << "Choose size of your multidimensional array [matrix]: ";
int size;
cin >> size;
int arr[size][size];
cout << "Now enter your data [Respectively] \n";
for(int d=0; d<size; d++)
{
for(int j=d+1; j<size; j++)
{
if (d==j)
{
arr[d][j] = 0;
}
else if(j<d) // here laid the problem
{
arr[d][j] = arr[j][d];
}
else
{
cin >> arr[d][j]; // Filling matrix
}
}
}
// print matrix
for(int d=0; d<size; d++) {
for(int j=0; j<size; j++)
cout << arr[d][j] << " ";
cout << '\n';
}
return 0;
}
This below is even cleaner, gets rid of the conditional inside the inner loop, thank you @ThomasSablik
#include <iostream>
using namespace std;
int main()
{
cout << "Choose size of your multidimensional array [matrix]: ";
int size;
cin >> size;
int arr[size][size];
cout << "Now enter your data [Respectively] \n";
for(int d=0 ; d<size ; d++)
{
arr[d][d]=0;
for(int j=d+1; j<size; j++)
{
cin >> arr[d][j];
arr[j][d]=arr[d][j];
}
}
// print matrix
for(int d=0; d<size; d++) {
for(int j=0; j<size; j++)
cout << arr[d][j] << " ";
cout << '\n';
}
return 0;
}
Upvotes: 2