C++ || Snippet – How To Find The Minimum & Maximum Of 3 Numbers, Print In Ascending Order
This page will demonstrate how to find the minimum and maximum of 3 numbers. After the maximum and minimum numbers are obtained, the 3 numbers are displayed to the screen in ascending order.
This program uses multiple if-statements to determine equality, and uses 3 seperate int varables to store its data. This program is very basic, so it does not utilize an integer array, or any sorting methods.
NOTE: If you want to find the Minimum & Maximum of numbers contained in an integer array, click here.
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
// ============================================================================ // Author: K Perkins // Date: Apr 29, 2012 // Taken From: http://programmingnotes.org/ // File: min_mid_max.cpp // Description: Demonstrates how to find the minimum & maximum of 3 numbers // ============================================================================ #include <iostream> using namespace std; int main() { // declare variables int a=0; int b=0; int c=0; int max=0; int min=0; int middle=0; // get data from user cout<<"Please enter 3 numbers: "; cin >> a >> b >> c; // display information back to the user cout <<"The numbers you just entered are: "<<a<<" "<<b<<" "<<c<<endl; // check for the highest number if(a > b && a > c) { max = a; } else if(b > a && b > c) { max = b; } else { max = c; } // check for the lowest number if(a < b && a < c) { min = a; } else if(b < a && b < c) { min = b; } else { min = c; } // use the 'min' and 'max' variables from above ^ to find // the 'middle' value if((max == a && min == b) || (max == b && min == a)) { middle = c; } else if((max == b && min == c) || (max == c && min == b)) { middle = a; } else { middle = b; } // display data to the screen cout<<"nThe maximum number is: "<<max; cout<<"nThe minimum number is: "<<min; cout<<"nThe numbers in order are: "<<min<<" "<<middle<< " "<<max<<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Please enter 3 numbers: 89 56 1987
The numbers you just entered are: 89 56 1987The maximum number is: 1987
The minimum number is: 56
The numbers in order are: 56 89 1987
Leave a Reply