Hi all :) I wrote a code to ascend any three integers. Problem is the code does not output the numbers in ascending order all the time. What am I doing wrong? here is my code :
// This program will prompt user to enter any three integers and then out integers in ascending order
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int num1,num2,num3;
cout << "Enter the first number: " << endl;
cin >> num1;
cout << endl;
cout << "Enter the second number: " << endl;
cin >> num2;
cout << endl;
cout << "Enter the third number: " << endl;
cin >> num3;
cout << endl;
if (num1 < num2)
if (num2 < num3)
if (num3 > num1)
{
cout << "The ascending order is: "<< num1 <<" " << num2 << " " << num3 << endl;
}
if (num1 > num2)
if (num2 < num3)
if(num3 < num1)
{
cout << "The ascending order is: "<< num2 <<" " << num3 << " " << num1 << endl;
}
if (num1 < num2)
if (num2 > num3)
if(num3 < num1)
cout << "The ascending order is: "<< num3 <<" " << num1 << " " << num2 << endl;
system("pause");
return 0;
With 3 numbers, there are 6 possible permutations:
ABC
ACB
BAC
BCA
CAB
CBA
You are only outputting 3
And you're approaching this the wrong way. Rather than trying to make a maze of if statements and copy/paste it for each permutation, just sort the data and then print it normally.
IE, if num1 is > num2, then swap num1 and num2. Repeat until all 3 are sorted, then just print them all.
(that is, of course, assuming you can't use the STL sort() function which would do this for you...)