Max & Min

Apr 13, 2017 at 10:24pm
Given the integer variables x, y, and z, write a fragment of code that assigns the smallest of x, y, and z to another integer variable min.

Assume that all the variables have already been declared and that x, y, and z have been assigned values ).
This should work right?
1
2
3
4
5
6
if(x>y)
y=min;
else x=min;
	
if (min>z)
z=min;


Given the integer variables x and y, write a fragment of code that assigns the larger of x and y to another integer variable max.

1
2
3
4
5
if(x>y)
x=max;
else
y=max;


Apr 13, 2017 at 11:12pm
Try it, test it, see if it works. Spoiler, it doesn't.

First, you are setting y equal to min or x equal to max, as examples, you should be setting max equal to the value of x. Next, neither min nor max are initialized to any value, so when you use them for comparison it doesn't work. Your logic is also bad. I would suggest something along the lines of:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
	//min
	min = x;
	if (min > y)
		min = y;
	if (min > z)
		min = z;


	//max
	max = x;
	if (max < y)
		max = y;
	if (max < z)
		max = z;
Last edited on Apr 13, 2017 at 11:31pm
Topic archived. No new replies allowed.