I am new to c++ and need help writing a program that will sort three integers in descending order. My program will compile fine but if you mix up the integers it will print one of the integers twice. You have to put the integers from least to greatest for it to work right everytime. Here is what i have so far. Thanks for the help!
#include <iostream>
using namespace std;
int main()
{
int num1,num2,num3,largest,inbetween,smallest;
cout << "Enter three integers: " << endl;
cin >> num1 >> num2 >> num3;
largest = num1;
if (num2 > largest)
largest = num2;
if (num3 > largest)
largest = num3;
inbetween = num2;
smallest = num3;
if (num2 < smallest)
smallest = num2;
if (num1 < smallest)
smallest = num1;
cout << "Integers in decending order: ";
cout << largest << "\t" << inbetween << "\t" << smallest << endl;
you just set 'inbetween' to num2, you never actually check num2's value. You can find 'inbetween' by calculating the second highest or second lowest value, or taking the only remaining value which isnt 'smallest' or 'largest'
It's probably going to be easiest if you put the three variables in an array for starters, that way you can actually start to consider using a simple sorting algorithm.
Have a look at insertion sort, it's probably the easiest to code, something like this should do:
#include <iostream>
usingnamespace std;
int main()
{
int p;
int largest;
int array[3];
//Asks for and accepts user input for three numbers
cout << "Please enter three numbers";
cin >> array[0] >> array[1] >> array[2];
//For every value in the list (except the first one
for( int i = 1; i < n; i++ )
{
//Temporary variable
p = i;
largest = array[i];
//While the adjacent array item is smaller, change the current array item to the smaller item
while( array[p-1] < largest )
{
array[p] = array[p-1];
if( p == 0)
break;
else
p--;
}
array[p] = largest;
}
//Prints out all the sorted items
for( int i = 0; i < n; i++ )
cout << array[i] << " - ";
return 0;
}