sorting number in acsending order

hi

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.
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
#include<iostream>

using namespace 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;
   }
   else if (a > b && b > c) 
   {
      cout<<c<<b<<a;
   }
   
   else if (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
Last edited on
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.

http://en.wikipedia.org/wiki/Bubble_sort

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"
Just look at it as if it were a Sudoku game:

1
2
3
4
5
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. 
Topic archived. No new replies allowed.