### Thread: [HELP] finding largest of 5 integers without if statement

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2013
Posts
2
Rep Power
0

#### [HELP] finding largest of 5 integers without if statement

first post here, im a freshman going for a computer science degree and need a little help here to finish this program..

#include <stdio.h>
/* This function returns the larger of a and b. */
int larger(int a, int b)
{
if(a > b)
return a;
else
return b;
}

/* This function returns the largest of x1, x2, x3, x4, and x5. */
int max(int x1, int x2, int x3, int x4, int x5)
{
/* Your code comes here. */
/* Do not use any if statements in this function. */
}

main()
{
int a, b, c, d, e;
int largest;
printf("Enter five integers: ");
scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);
largest = max(a, b, c, d, e);
printf("\nLargest = %d\n", largest);
}

Thank you for the help in advance
2. Piece of cake. HINT: call larger() from max() 4 times. Also pay attention to what larger() returns.
3. If you're permitted to use a ternary operator
condition ? true_expression : false_expression)
then
the problem is easily solved
else
you could increment each number. The first one to have its sign change....hmm....you'd still need a detection mechanism.

Or you could subtract one from the other....that's how the INTEL cmp opcode works anyway. Save the flags, discard the result.

I keep returning to ?: .

oh, you're permitted to use larger[/edit]
Last edited by b49P23TIvg; April 15th, 2013 at 06:46 PM.
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
101
Rep Power
0
I used the ternary operator.

Code:
```#include<stdio.h>

int data[9] = {5,7,5,7,8,5,10,8};

int max(int nums[])
{
int largest = nums[0];
int i;
for(i = 1;i <= sizeof(data) / 4;i++)
{
largest = nums[i] > largest ? nums[i] : largest;
}
return largest;
}

int main()
{
printf("%d",max(data));
getchar();
return 0;
}```
5. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2013
Posts
2
Rep Power
0
sorry for my ignorance, but for the max function is it something like returning larger to max and voiding b multiple times? (dont know if voiding is the right word)

nvm figured it out, heres the solution if for some off chance someone googles to this :P

int temp1, temp2, temp3, temp4;

temp1 = larger(a, b);
temp2 = larger(c, d);
temp3 = larger (e, temp1);
return temp3;
6. So, mcydes, just what would that fine algorithm return if the largest value happened to be in d or in c?

Comprehensive testing, though hard on the index finger, is worthwhile.