Make a loop and iterate over the array. While looping, use comparison statements to compare the elements to each other.
Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393
like this:
#include <iostream>
using namespace std;
void main()
{
int minimum;
int numbers[4]={10,12,10,14};
for (int i=0; i<4; i++)
{
if(numbers[i]<numbers[i+1])
{
minimum=numbers[i];
cout << "minimum = " << minimum << endl;
}
}
}
This isn't a sort, this is a straight comparison. It is similar to what I suggested you try, but not quite correct.
1. Trace your code by hand, what happens when i == 3? You end up trying to access numbers[4] which does not exist. Usei to determine which iteration of the loop you are on. If you determine that it is the first iteration of the loop, store numbers[i] directly to minimum. On the later iterations, use the comparison statement and compare numbers[i] to the current value of minimum.
begin for loop
if first iteration of loop detected
assign first array element to minimum
else
if current element less than current minimum
assign current element to minimum
end if
end for
display minimum
2. Your scoping braces are not correct. Your display statement for the minimum is inside your if statement which is nested inside your for loop. This statement should be independent and not execute repeatedly or conditionally. It should only execute once and its execution should be guaranteed. Move the statement outside your for loop completely.
Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393