easy way to find the smallest variable?

Hi all,

I have a question regarding the simplest method to find the smallest variable given the variables: x, y, z. Assume that all three variables are positive and distinct. And then assign the smallest value to the variable: smallest, and store the largest to the variable: largest.

The way I wrote the code is, imo, quite complicated, eg:

i have to use six if/else-if statements to check for:
x < y < z
x < z < y
y < x < z
y < z < x
z < x < y
z < y < x

But, this is simply a comparison between three variables, what if there are 10 or 100 variables to compare? That would be way to complex. So, is there a simpler way to code this?
Below is the only way comes into mind.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  #include <iostream>
using namespace std;

int main()
{
	int x, y, z;
	int smallest, largest;
	
	if ( x<y && y<z )
	{
		smallest = x;
		largest = z;
	}
	else if ( x<z && z<y )
	{
		smallest = x;
		largest = y;
	}
	else if ( y<x && x<z)
	{
		smallest = y;
		largest = z;
	}
	else if ( y<z && z<x )
	{
		smallest = y;
		largest = x;
	}
	else if ( z<x && x<y )
	{
		smallest = z;
		largest = y;
	}
	else if ( z<y && y<x )
	{
		smallest = z;
		largest = x;
		
	}
	return 0;
}
Last edited on
Have you studied functions as yet?
oh no, not yet. I guess that chapter contains the answer to my question right?

Ill check it out, thanks for the info :)
Last edited on
Using a function will greatly simplify the logic required to solve this problem.

Topic archived. No new replies allowed.