简体   繁体   中英

Find smallest element in array

In an array of N elements (N is given), find the smallest element from the first zero element to the end of the array. If there are no zero elements in the array, display a message about it. Can someone fix this for me please?

  #include<iostream>

  using namespace std;

  int main() {
    int i, n;
    cout << "N= "; cin >> n;
    if (n > 0) {
      int *a = new int[n];
      for (i = 0; i < n; i++) {
        cin >> a[i];
      }
      for (i = 0; i < n; i++) {
        if (a[0] > a[i])
          a[0] = a[i];
      }
      cout << "\nMin:" << a[0];
      delete[] a;
    }
    return 0;
  }

I couldn't find the problem with your code so I am showing how I approached finding a minimum element from a given array:

#include<iostream>
using namespace std;

int main()
{
    int n;
    cin>>n;

    int arr[n];
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }

    int minNo=INT16_MAX;               // to assign max. possible value to minNo
    
    for(int i=0;i<n;i++){
        minNo=min(arr[i],minNo);
    }
    cout<<minNo<<endl;

    return 0;
}

You can simply check it in the same loop in which you looking for smallest element.

#include <iostream>
#include <climits>

using namespace std;

int main() {
    int i, n;
    bool isZeroElement = false;
    cout << "N= "; cin >> n;
    if (n > 0) {
        int *a = new int[n];
        for (i = 0; i < n; i++) {
            cin >> a[i];
        }
        int minElement = INT_MAX;
        for (i = 0; i < n; i++) {
            if (!isZeroElement && a[i] == 0)
            {
                isZeroElement = true;
                continue;
            }
            
            if (isZeroElement && minElement > a[i])
                minElement = a[i];
        }
        if (!isZeroElement)
            cout << "There is no zero element in the array\n";
        else
            cout << "\nMin:" << minElement;
        delete[] a;
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM