You are here:

# C++/min of 4 values

Question
Hello. I posed this question to Eddie actually and he replied but I still needed feedback and he couldn't receive anymore Qs. Really do hope you could help me out though. Anyway, I actually tried that method..(the method Eddie suggested) but it gives me the same problem.

Once again, say if, x1=6.7, x2=6.5, x3=8, x4=3

Then if I assume min=x1 and then proceed on with

if (x2 < min) (check, it's true!)
so, min = x2;

else if (x3 < min) (NOT TRUE)
so, min = x3;

else if (x4 < min) (TRUE!)
then, min = x4;

So now we see that there's two TRUEs. And considering the first 'if' statement is already true, it automatically ignores the rest and executes x2=6.5 as its min value. BUT, we know that the true min value should however, be x4=3.

Sigh. I'm confuse. I've been going all about trying everything. What do you suggest?

I tried something else though..

double minimum(double x1, double x2, double x3, double x4)
{
double min;

if (x1<x2)
{
if (x1<x3)
{
if (x1<x4)
{
min=x1;
}
}
}

else
{
if (x2<x3)
{
if (x2<x4)
{
min=x2;
}

else
{
min = x4;
}
}

else
{
if (x3 < x4)
{
min = x3;
}

}
}

return min;
}

This works really fine EXCEPT it reads only one sample correctly. (I actually have two sample.) It reads one min value correctly and the other, it gives a really huge exponential value. Really puzzling..

-------------------------

Followup To

Question -
Hey Eddie,

This has been bugging me. How do I detect the minimum of 4 given values? This is the fraction of what I did which I know is not right 'cause it obviously doesn't give the right answer.

i have my values initialised in my main where
x1=6, x2=4, x3=4.3, x4=7.9

double minimum(double x1, double x2, double x3, double x4)
{
double min;
min = x1; //assuming x1 is min

if (x2 < min)
{
min = x2;
}
else
{
if (x3 < min)
{
min = x3;
}

else
{
if (x4 < min)
{
min = x4;
}

}
}

return min;
}

I didn't exactly get the right answer. It works for some because coincidently, that value happened to be the lowest. Don't think I'm explaining myself well.. but the bottom line is, how do I create a funtion that detects the minimum of 4 values. It works if there's 3 values, or 2.. but not 4. And I've been figuring out and still not too sure about it.

Looking forward for a feedback. Thank you so much!

Hello epic, thank you for the question.

Your problem if the fact that you are not using else if's in your conditional statement. The execution flow is not working how you think it is. Here is what it should look like (note AllExpert's lack of indentation preservation):

double minimum(double x1, double x2, double x3, double x4)
{
double min = x1;

if (x2 < min)
{
min = x2;
}
else if(x3 < min)
{
min = x3;
}
else if(x4 < min)
{
min = x4;
}
return min;
}

That should have you good to go. Please don't hesistate to ask another question if you do not understand something.

I hope this information was helpful.

- Eddie

Well the problem you both have is using else at all. In an if {...} else if {...} else if {...} else {...} construct only _one_ clause will ever be executed but you may need to execute more than one clause to determine the minimum of four values. For example given the values 4, 3, 2, 1 for x1, x2, x3 and x4 you have to check and modify min each time:

min = x1;          // min = 4
if ( x2 < min ) min = x2; // true, set min = x2 (==3)
if ( x3 < min ) min = x3; // true, set min = x3 (==2)
if ( x4 < min ) min = x4; // true, set min = x4 (==1)

Note that I have used a very terse style, as I think in this case it gets the point across admirably. In general I do _not_ like not enclosing such clauses in { and } as adding any other code to any of the clauses would force their use (e.g. debug only code to log the value of min to check the code is doing what you think). You could also use the tertiary conditional assignment operator ?: thus:

minA = ( x1 < x2 ) ? x1 : x2;
minB = ( x3 < x4 ) ? x3 : x4;
min = (minA < minB ) ? minA : minB;

Or you could use the std::min function (include <algorithm>):

min = std::min( std::min(x1,x2), std::min(x3,x4) );

Which probably comes down to pretty much the same thing as the ?: example.

In fact you probably do not need to keep min around, you could just return the result directly from your function:

double minimum(double x1, double x2, double x3, double x4)
{
return std::min( std::min(x1,x2), std::min(x3,x4) );
}

Your example does not scale well. Suppose you wanted the minimum value from a 1000 values. In such cases you would pass the values to find the minimum of in some sort of collection, for example maybe you would use a std::vector (single dimension array):

double minimum( std::vector<double> const & values )

To find the minimum you would use a loop:

{
double minVal( values[0] );
for ( unsigned int i=1; i<values.size(); ++i )
{
if ( values[i] < minVal )
{
minVal = values[i];
}
}
return minVal;
}

The above assumes the vector has at least one element.

However the C++ standard library can help here too as it has a min_element algorithm (include <algorithm>) to return the element having the minimum value from a range of values:

double minimum( std::vector<double> const & values )
{
return *std::min_element( values.begin(), values.end() );
}

Please note that I have not tried any of the above code examples so they may contain typos or errors, for which I apologise. Hope you find this of use.

C++

Volunteer

#### Ralph McArdell

##### Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

##### Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials