# Thread: Program to find largest of 3 numbers

1. ## Program to find largest of 3 numbers

Is it possible to do this with only 2 variables?

Thanks

2. Why don't you try to do it with only two variables, and see if you can?

3. I've come to the conclusion that it's not possible as you are comparing three numbers.

4. Perhaps the challenge was 2 comparisons (which is possible), not 2 variables (which isn't).

5. Apparently you can use arrays.

6. Originally Posted by stuartbaggs
Apparently you can use arrays.
What about packed data? ....You could do it with one variable

7. Originally Posted by Salem
Perhaps the challenge was 2 comparisons (which is possible), not 2 variables (which isn't).
I could post a counter example - albeit one that makes rather specific assumptions about where the program obtains the three values from, and what it does with the maximum. But I'll allow people to enjoy the challenge.

8. Or, if you count the three input values in an array as one variable, the trivial solution uses exactly two variables and two comparisons.

Edit: Since qny posted one below, I'll post this one too.
Code:
```double maximum_of_three(const double *numbers)
{
double max = *numbers;

if (*(++numbers) > max)
max = *numbers;

if (*(++numbers) > max)
max = *numbers;

return max;
}```
and for any number of values using just three variables and (numbers - 1) comparisons (of numbers; (2*numbers - 1) if you count the loop condition comparison too):
Code:
```double maximum(const double *numbers, size_t count)
{
double max = *numbers;

while (count-- > 1)
if (*(++numbers) > max)
max = *numbers;

return max;
}```

9. Originally Posted by grumpy
I could post a counter example
Allow me

Code:
```input A                              // 1st number
input B                              // 2nd number
if A < B let A = B
input B                              // 3rd number
if A < B print largest is B
else print largest is A```

10. Originally Posted by qny
Allow me
Indeed