Glenn Jordan Chia Glenn Jordan Chia - 1 month ago 16
C++ Question

Find the lowest of 4 variables using only else-if statements, C++

I just started c++ not too long ago. I want to find the lowest of 4 variables using only if-else statements. So far this is what i could think of. Is there anyway to shorten this?

float lowest;

if (assignment1<assignment2 && assignment1<assignment3 && assignment1<assignment4)
assignment1 == lowest;


else if (assignment2<assignment1 && assignment2<assignment3 && assignment2<assignment4)
assignment2 == lowest;



else if (assignment3<assignment1 && assignment3<assignment2 && assignment3<assignment4)
assignment3 == lowest;



else
assignment4 == lowest;

Answer

Are you allowed to do multiple assignments to lowest? If so:

float lowest = assignment1;

if (assignment2 < lowest)
    lowest = assignment2;

if (assignment3 < lowest)
    lowest = assignment3;

if (assignment4 < lowest)
    lowest = assignment4;

By keeping the smallest value inside lowest, we can simply check each value against lowest, and update lowest when a smaller value is found.