I have this code so far, but the problem is that after the user enter 10 numbers, it wont sort the number in ascending or descending order
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
//variable declaration
int iNumbers[10];
int iEntry=0;
int x=0;
printf("Enter 10 numbers\n");
for (x=0; x < 10; x++) {
scanf("%d", &iNumbers[x]); //user for loop to scan every value in the array
}
printf("\n\nWhich order would you like to see your numbers?");
printf("\n1)\tAscending\n");
printf("\n2)\tDescending\n");
scanf("%d", &iEntry);
switch(iEntry) {
case 1:
printf("\n\n%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",iNumbers[0],iNumbers[1],iNumbers[2] ,iNumbers[3],iNumbers[4],iNumbers[5],iNumbers[6],iNumbers[7],iNumbers[8],iNumbers[9]);
break; //prints all the numbers in the array in ascending order
case 2:
printf("\n\n%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",iNumbers[9],iNumbers[8],iNumbers[7],iNumbers[6],iNumbers[5],iNumbers[4],iNumbers[3],iNumbers[2],iNumbers[1],iNumbers[0]);
break; //prints all the numbers in the array in descending order
}
system("pause"); //pauses system
return 0;
} //end of main function
No, it won’t sort the number because you haven’t written the code to do it yet!
Your code to print them out in forward or reverse order is okay, but it’s based solely on the order in which you input the numbers.
If you want them sorted numerically rather than positionally, you need to either look into the
qsortfunction (if you just want it sorted) or look into sort algorithms in general if you need to code up your own (such as homework).For an example of the latter, you can use the very simple pseudo-code below. It’s a bubble sort so not really suitable for serious use but it’s more than adequate for small data sets and/or homework:
If, as you mention in a comment, you cannot use a bubble sort, you should google for one of the other sort algorithms and code it up.
But I’d try to stick to those which are simple to understand. Next step up from bubble sort would probably be selection sort, pseudo-code below:
This has the advantage of only swapping once per major pass rather than (possibly) many times. It does the minor pass only to find which index should be placed at a given position and then swaps.
The only difference then between your two cases (ascending and descending) would be the use of
>instead of<in the comparison function.