I am trying to complete the following program exercise :
write a program that prompts the user to input three numbers. The program should then output in asceding order. I could not find a proper solution for this exercise.
However, I have completed the exercise, but something is definitely wrong, when I enter a negative number, the numbers are not sorted properly.
#include<iostream>
usingnamespace std;
int main()
{
int a,b,c;
cout<<"Please enter three numbers: ";
cin>>a>>b>>c;
if (a < b && b < c)
{
cout<<a<<b<<c;
}
elseif (a > b && b > c)
{
cout<<c<<b<<a;
}
elseif (a < b && b > c)
{
cout<<a<<c<<b;
}
else
{
cout<<"You didnt enter an alphabet";
}
return 0;
The thing is..I am using trial and error method..to derive the equations..but there must be some logic/probability..that I cant get ..need some help here
Well there are more than three possibilities for sorting three numbers. The bubble sort would work well enough in this case and it is simple enough to start with, it is a typical sorting method taught early on.
That teaches you about it but basically it goes like this. You've got a nested loop, one for the number of numbers you have and one for the number you are moving. You take the first number and test it against the number next to it, if it is bigger then move it over by utilizing a temp variable and then test again until they are all moved over or decided that they are small then the number to their right.
Also, that you should check up on. 1.) You don't have a '}' at the end of your program. 2.) On line 26 you say "You didn't enter an alphabet" I think you mean "a number" not "an alphabet"
int a=3,b=2,c=1; //1-3 are representative for the smallest, middle and biggest number
//at first we have the following possibilities: a: 1|2|3 b: 1|2|3 c: 1|2|3
if (a>b)swap(a,b); //now a can't be the highest and b not the lowest, so: a: 1|2 b: 2|3 c: 1|2|3
if (b>c)swap(b,c); //now b can't be the highest and c not the lowest, so: a: 1|2 b: 1|2 c: 3 (sole remaining candidate)
if (a>b)swap(a,b); //now a is the lowest and c was the only remaining candidate for 3, leaving 2 for b - done.