Search code examples
c++arraysminimum

Need to find the minimum value of a 4x2 array while ignoring the diagonal


I need to find the lowest value in an array that isn't in the main diagonal, I have written some code but it seems to pick either the second or the last value only (depending on which one is the lowest).

here is my code:

#include<iostream>
using namespace std;
int main()
{
    int arr[4][2];
    int Min,i,j;
    cout<<"Type 8 numbers";
    for (i=0;i<4;i++)
    {
        for (j=0;j<2;j++)
        {
            cin>>arr[i][j];
            Min=arr[0][1];
            if(i!=j and Min > arr[i][j])
            {
                Min=arr[i][j];
            }
        }
    }
    cout<<"The values of the array are: \n";
    for (i=0;i<4;i++)
    {
        cout<<"\n";
        for (j=0;j<2;j++)
        {
            cout<<arr[i][j]<<"\t";
        }
    }
    cout<<"The lowest value is: "<<Min;
}

If I type 1-8 the returned value is 2, if I type 8-1 the returned Value is 1, in both of these cases the code is working as I intended, but if I type something like 8,6,4,1,2,3,4,5, the lowest value is returned as 5, I'm very new to coding and would appreciate any help.


Solution

  • The line

    Min=arr[0][1];
    

    is bad because

    • It reads uninitialized arr[0][1] when i = 0, j = 0.
    • It writes arr[0][1] to Min unconditionally, even if current Min is smaller than that.

    Instead of this:

    Min=arr[0][1];
    if(i!=j and Min > arr[i][j])
    {
        Min=arr[i][j];
    }
    

    This will work, for example:

    if(i!=j and ((i==0 and j==1) or Min > arr[i][j]))
    {
        Min=arr[i][j];
    }