• Articles
  • Maximum of three numbers? (For Beginners
Published by
Dec 21, 2011 (last update: Jan 18, 2012)

Maximum of three numbers? (For Beginners)

Score: 3.4/5 (390 votes)
*****
Note: This tutorial is targeting beginners that are learning C++ and programming.

How can I get the maximum of 3 numbers using the C++ programming language.

Of course you can get the maximum of 3 numbers in many ways matter of fact there can be more than one solution and they are all correct but to this specific problem I found a really interesting solution.


Here is the code I will explain it below:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* Function maximum definition */
/* x, y and z are parameters */
int maximum(int x, int y, int z) {
	int max = x; /* assume x is the largest */

	if (y > max) { /* if y is larger than max, assign y to max */
		max = y;
	} /* end if */

	if (z > max) { /* if z is larger than max, assign z to max */
		max = z;
	} /* end if */

	return max; /* max is the largest value */
} /* end function maximum */


The code is really simple, it assumes that any of the 3 values is the largest then compares the other 2 values to the first value.
if one of the 2 values is greater than the one we assumed then the max is equal to that value.

If you have any questions related to this article you can contact me via

Twitter:
_mFouad
mail: mfouad91@gmail.com