Miek Posted December 14, 2010 Posted December 14, 2010 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 More sharing options...
WhenKittensATK Posted December 14, 2010 Posted December 14, 2010 (edited) 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 December 14, 2010 by Krazyxazn Share this post Link to post Share on other sites More sharing options...
CheeseMan42 Posted December 15, 2010 Posted December 15, 2010 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 More sharing options...
Miek Posted December 15, 2010 Posted December 15, 2010 Thank you both! Sorry for the late reply. My CS final is DONE. It was a lengthy exam, but I think I did alright. Share this post Link to post Share on other sites More sharing options...
Recommended Posts
Please sign in to comment
You will be able to leave a comment after signing in
Sign In Now