?
Solved

Smallest number in an array

Posted on 2005-04-25
1
Medium Priority
?
2,817 Views
Last Modified: 2012-05-05
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
0
Comment
Question by:David_4321
1 Comment
 
LVL 8

Accepted Solution

by:
_corey_ earned 380 total points
ID: 13861335
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question