Interview Question: Finding Maximum

Sample Question #268 (programming – C/C++)
 
Write a one-line C or C++ statement that stores in x the larger of two numbers, x and y, without using the if statement. (If x=y, return x.)
Advertisements
This entry was posted in Sample Qs. Bookmark the permalink.

6 Responses to Interview Question: Finding Maximum

  1. Brett says:

    ANSWER
     
    x = (x>=y) ? x : y;
     
    Comment: This question would be trivial for people familiar with C or C++. The in-line condition statement is used extensively by experienced programmers and is something every C/C++ programmer should know.
     

  2. Brett says:

    BTW, when you’re asked to write sample programming code, don’t forget any end-of-statement semicolons or other elements that make a statement in the chosen language valid. On the other hand, you need not initialize or even declare variables if they’re clearl from the context, as in this sample question.

  3. Nathan says:

    for this case
     
    z = std::max(x, y);
     
    clearly defines the intent, without resorting to the tenary operator. ?: has it’s uses but the min/max pattern should not be one of them.

  4. jixiang says:

    How about
    x = ( x + y + abs( x – y ) ) / 2

  5. Nathan says:

    That doesn’t work if the intermediate overflows. Your algorithm produces -1 for:
    int x = INT_MAX;int y = INT_MAX – 1;

  6. Suwandi says:

    I’m not that familiar with C++. I guess this would do for both C++ and Matlabx = (x>=y)*x + (x<y)*y;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s