Smallest number in an array

Hey everyone, just a small problem, im trying to find the smallest value in an array, but keep getting 0, can someone please help?


#include <iostream>
using namespace std;

void smallest (int x[], int size);


int main()

{
       int *array;
     int arraySize, i;
      cout << "Please input array size:" << endl;
     cin >> arraySize;

     array = new int[arraySize];

     cout << "Please input the array elements: " << endl;
     for (i = 0; i < arraySize; i++)
          cin >> array[i];
       smallest(array,arraySize);

       return 0;
}

void smallest (int x[], int size)    
{
   int smallest = 999;  
   for (int i=0; i < size; i++) {
         if (x[i] < smallest ) {
         smallest = i;
      }
   }
   cout << smallest;
}

Ta,

David
David_4321Asked:
Who is Participating?
 
_corey_Connect With a Mentor Commented:
David,

  The issue is that you're comparing to 9999 instead of the first element, and that you're assigning smallest with the index instead of the value in the array:

void smallest (int x[], int size)    
{
   int smallest = x[0];  
   for (int i=0; i < size; i++) {
        if (x[i] < smallest ) {
         smallest = x[i];
      }
   }
   cout << smallest;
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.