adiletgov
adiletgov

Reputation: 51

C++ How to find min and max values in a one-dimensional array of n elements?

Write a program that asks a user to input an integer n. The program should prompt the user to input n integers and store them in a one-dimensional array. Then the program should output the minimum and maximum elements in the array.

int main()
{
    int n,a,b;
    cin>>n;
    int ma=0,mi=0;
    int num[n];
    cin>>num[0];
    for(int i=1;i<n;i++)
    {
        cin>>num[i];
        a=num[i];
        b=num[i-1];
        if(a>b)
            ma=a;
        if(a<b)
            mi=a;
    }

    cout<<mi<<endl;
    cout<<ma;
}

When given elements, it doesn't show the min and max values correctly. Where is my mistake?

Upvotes: 0

Views: 2795

Answers (2)

Christopher Yeleighton
Christopher Yeleighton

Reputation: 454

I would try the following code:

std ::vector < int > v (n);
std ::copy_n (std ::istream_iterator < int, char > (cin), begin (v), n);
auto const r ((std ::minmax_element) (begin (v), end (v)));
return std ::cout << * r .first << '\n' << * r .second ? EXIT_SUCCESS: EXIT_FAILURE;

Upvotes: 1

ZanyBaka
ZanyBaka

Reputation: 189

You missed that the first value in your algo will never be set as a min or as a max value. Let's assume all the numbers are positive ones

int main()
{
    int n;
    cin>>n;
    int ma=0,mi=2147483647;
    int num[n];
    for(int i=0;i<n;i++)
        {
            cin>>num[i];
            if(num[i] > ma)
                ma = num[i];
            if(num[i] < mi)
                mi = num[i];
        }


    cout<<mi<<endl;
    cout<<ma;
}

Upvotes: 3

Related Questions