Jump to content

Just one last thing.


Miek

Recommended Posts

This was part of my lab test (over two weeks ago). It was the only thing that I didn't get, and it's driven me a little crazy since.

 

There were ten values in the array, all int types. I had to design a function that would return the smallest value from the array.

 

I *could* have just used a plethora of if-else statements, but that got really clunky really quickly.

 

I tried using a looped if statement along the lines of

 

for (int i; i<10, i++)
{
if (array_name_here[i] < array_name_here[i+1])
cout << array_name_here[i] << endl;
}

 

...But, unsurprisingly, it didn't work and ended up returning more than one value.

 

All I'm wondering is what I could have done to properly return the smallest value in an efficeint way. I've been thinking on it since, and all I've succeeded in doing was making myself feel even more dumb and distract myself from studying for my remaining final exams.

Share this post


Link to post
Share on other sites

In C:

 

int findMin( int p[] )
{
    int i, 
        min = p[0]; // set minimum value to 1st number in array

    for(i = 1; i < 10; i++) // run from 2nd number in array till end
    {
         if(min > p[i]) // if minimum variable's value is larger than p[i], set p[i] value to minimum
              min = p[i];
    }
    return min;
}

 

There are a couple of ways to program this, but this is one. Hopefully you can translate this code from C to C++ or at least understand the basic layout.

Edited by Krazyxazn

Share this post


Link to post
Share on other sites

See above.

 

The reason your code "returned" (printed out) several values is that it was only comparing each value to the one after it. You need to go through the whole thing as in the example above to only get one value.

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
×
×
  • Create New...