ilovesayyora ilovesayyora - 2 months ago 7
C Question

Find second largest number

Yes, there are loads of people have already discussed this problem but this one seems to be a bit extraordinary. Program should find the second largest number from the five ones entered by user. We cannot use neither

loops
nor
if
statements. Also cannot use
arrays
and
goto's
, but can use ternary operator. The sample of I/0 :

Input :
34 -52 87 -12 20
Output:
34


Input :
-87 52 87 87 20
Output:
87


As you see user can input two same numbers and program should be able to treat it this way. This is C programming.

#include <stdio.h>
#include <stdlib.h>


int main(void)
{

int i1, i2, i3, i4, i5;
int max, second_max;

scanf("%d %d %d %d %d", &i1, &i2, &i3, &i4, &i5);

max = i1;
max = (i2 > max) ? i2 : max;
max = (i3 > max) ? i3 : max;
max = (i4 > max) ? i4 : max;
max = (i5 > max) ? i5 : max;

second_max = i1;
second_max = (i1 > second_max && i1 < max) ? i1 : second_max;
second_max = (i2 > second_max && i2 < max) ? i2 : second_max;
second_max = (i3 > second_max && i3 < max) ? i3 : second_max;
second_max = (i4 > second_max && i4 < max) ? i4 : second_max;
second_max = (i5 > second_max && i5 < max) ? i5 : second_max;




printf("\nmax: %d", max);
printf("\nsecond_max : %d", second_max);




return 0;
}


Here i can find everything, when it comes to the second sample of output it fails. I have an experience of programming but cannot solve this problem since morning

Answer

Clearly, the problem is easy to solve if you can sort the numbers. So how do you sort the numbers using only ternary operators? The answer is known as a sorting network.

Here's what the code looks like:

#include <stdio.h>

void swap( int *a, int *b )
{
    int x = *a <= *b ? *a : *b;
    int y = *a <= *b ? *b : *a;
    *a = x;
    *b = y;
}

int main( void )
{
    int a = 1, b = 9, c = 3, d = 8, e = 3;

    swap( &a, &b );
    swap( &c, &d );
    swap( &b, &e );
    swap( &a, &b );
    swap( &d, &e );
    swap( &a, &c );
    swap( &c, &d );
    swap( &b, &c );
    swap( &c, &d );

    printf( "%d %d %d %d %d\n", a,b,c,d,e );
}

After the numbers are sorted, the second largest number is d.

Note that if you can't use subroutines and/or pointers, then just copy the body of the swap function and paste it into main nine times. Then change the letters as needed. Have fun with that.

Comments