int array_with_loop(vector data) { int i; data.push_back(5); data.push_back(7); data.push_back(3); data.push_back(-8); data.push_back(-2); int result = data[0]; for ( i =0; i < data.size(); i++ ) { if ( data[i] < result ) result = data[i]; } return result;
array_with_loop return lowest value in data vector .
Result is -8
inside the loop of:
for (i = 0; i < data.size(); i++)
{
if (data[i] < result)
result = data[i];
}
initial result is 5
loop 1: data[i] < result => 5 < 5 false
loop 2: data[i] < result => 7 < 5 false
loop 3: data[i] < result => 3 < 5 true, then result is assigned with 3
loop 4: data[i] < result => -8 < 3 true, then result is assigned with -8
loop 5: data[i] < result => -2 < -8 false
return result -8
Get Answers For Free
Most questions answered within 1 hours.