# Thread: Sorting Problems

1. ## Sorting Problems

This is a program that will ask the user for 4 numbers and sorts them from highest to lowest. It compiles fine with no errors but when I run the program it will not display the sorted array.
Code:
```//C source
#include <stdlib.h>
#define MAX 4

int main()
{
int i,a[MAX],t,k;

printf("Enter some numbers (4)\n>>> ");
for(i=0;i<MAX;i++)
scanf("%d",&a[i]);
for(k=MAX-1;k>0;k--){
for(i=0;i<k;i++){
if(a[i]>a[i+1]){
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
}
}
printf("The sorted array is\n>>>");
for(i=0;i<MAX;i++)
printf("%d",a[i]);
getch();
exit(0);
}```
I have done this one w/o the help of books or anything so there may be a logic error that I couldn't find but it seems to me like it should work.

Sample Excecution:
[running]
Enter some numbers (4)
>>> 7841

[/running]
If i hit control+z several times it will stop but turn out a number like 7469473631893648765. Really weird.

2. This I know Salem. I used a for loop to get the 4 digits that the user would input and used the for loop again to print out the 4 sorted digits.

3. fgets() seems to make it work...

Code:
```#define MAX 4

int main()
{
int i,a[MAX],t,k;
char buff[10];
printf("Enter some numbers (4)\n>>> ");
for(i=0;i<MAX;i++)
a[i] = atoi(fgets(buff, 10, stdin));
for(k=MAX-1;k>0;k--){
for(i=0;i<k;i++){
if(a[i]>a[i+1]){
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
}
}
printf("The sorted array is\n>>>");
for(i=0;i<MAX;i++)
printf("%d\n",a[i]);
getch();
return 0;
}```

Popular pages Recent additions