- 03. Make a program that asks for 3 numbers and places them in ascending order.
- 04. Make a program that asks for 3 numbers and puts them in descending order.
3 numbers in ascending order
We will store the numbers in the num1, num2 and num3 variables, and we will also use a temporary variable, an auxiliary, temp.The idea is this: we want to put the largest value entered in the num1 variable. The second largest value in variable num2 and the smallest in num3.
For this, let's make three comparisons:
- Compare num1 with num2, if num2 is greater, we invert the values. After this first test, we guarantee that the value contained in num1 is greater than num2.
- Compare num1 with num3, if num3 is greater, we invert the values. After this second test, we guarantee that the value contained in num1 is greater than num2 and now greater than num3.
- Now we have num2 and num3, if num3 is greater, we must invert the values, so we have the value contained in num2 greater than num3.
To do the value inversions, we will use the tutorial:
How to change the value of two variables
Our code is:
#include <iostream> using namespace std; int main() { int num1, num2, num3, temp; cout << "Number 1: "; cin >> num1; cout << "Number 2: "; cin >> num2; cout << "Number 3: "; cin >> num3; if(num2 > num1){ temp = num1; num1 = num2; num2 = temp; } if(num3 > num1){ temp = num1; num1 = num3; num3 = temp; } if(num3 > num2){ temp = num2; num2 = num3; num3 = temp; } cout <<num1<<" >= "<<num2<<" >= "<<num3<<endl; }
3 numbers in descending order
The logic is the same as above, we just want num1 to have the smallest value, num2 the second smallest value and num3 the greater value.Our code is:
#include <iostream> using namespace std; int main() { int num1, num2, num3, temp; cout << "Number 1: "; cin >> num1; cout << "Number 2: "; cin >> num2; cout << "Number 3: "; cin >> num3; if(num2 < num1){ temp = num1; num1 = num2; num2 = temp; } if(num3 < num1){ temp = num1; num1 = num3; num3 = temp; } if(num3 < num2){ temp = num2; num2 = num3; num3 = temp; } cout <<num1<<" <= "<<num2<<" <= "<<num3<<endl; }
No comments:
Post a Comment