Biggest and smallest of four integers (No arrays, no functions, fewest 'if' statements)

As per the OP's condition

But seeing that all we've covered in class for now are loops and decision statements. Is there a more elegant way of doing this? One which uses fewer ifs?

Only one if and one else if statement and one for loop can do this task. Simple and short!

#include <stdio.h>

int main()
{
    int num, max, min;

    printf ("Enter four numbers: ");
    scanf ("%d", &num);
    max = min = num;

    for (int i = 0; i < 3; i++)
    { 
        scanf ("%d", &num);
        if (max < num)
            max = num;
        else if (min > num)
            min = num;
    }

    printf ("The smallest and largest of given four numbers are %d and %d respectively.\n", min,  max);
    return 0;
}

Do a "manual" merge sort, or well, just the second bit of it:

Conceptually, a merge sort works as follows

  1. Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
  2. Repeatedly merge sublists to produce new sublists until there is only 1 sublist remaining. This will be the sorted list.

Merge sort merging step illustration

Code:

int a = 5, b=4, c=7, d=9;
int min_ab, min_cd, min;
min_ab = a < b ? a : b;
min_cd = c < d ? c : d;
min = min_ab < min_cd ? min_ab : min_cd;
printf("%d", min);

.. and similarly for max.

If you prefer, you can expand the ternary operator into if (a < b) { min_ab = a; } else { min_ab = b; } (spread over multiple lines for readability).

Merge sort has a complexity of O(n*log(n)), so you should at most need O(n*log(n)) ifs (see the wikipedia article on merge sort). According to Wikipedia, "... These are all comparison sorts, and so cannot perform better than O(n log n) in the average or worst case" (source), so I think this shouldn't be too far off in terms of minimum number of ifs.. Though you could try to see if manually performing one of the other algorithms results in fewer ifs ;-).


Try something like this

int main(void) {
    int a=-2,b=-3,c=-4,d=-5;
    int max=a,min=a;

    if(b>max){
        max=b;
    }else if(b<min){
        min=b;
    }
    if(c>max){
        max=c;
    }else if(c<min){
        min=c;
    }
    if(d>max){
        max=d;
    }else if(d<min){
        min=d;
    }
    printf("max: %d min : %d",max,min);
    return 0;
}

Demo

Tags:

C