Muhammed - 9 months ago 47

C Question

I have to sort three user inputted numbers in an array in ascending order. There are a couple of bugs.

A) I set it to only ask for three numbers, but I have to input 4 even though the program only sorts the first three.

B) I get a warning saying that my variable temp is unused, even though it clearly is.

C) the program sorts the first two numbers and then prints the second highest number again instead of the largest.

Here is the code:

`#include <stdio.h>`

#include <stdlib.h>

#include <string.h>

#include <ctype.h>

#include <math.h>

#include <time.h>

int main(){

int numbers = 3;

int NUM_ARRAY[numbers];

int counter = 0;

int sort = 0;

int temp = 0;

printf("Please enter three integers\n");

for(counter = 0; counter < numbers; counter++){

scanf("%d ", &NUM_ARRAY[counter]);

}

printf("Original Numbers\n");

for(counter = 0; counter < numbers; counter++){

printf("%d\n", NUM_ARRAY[counter]);

}

while(1){

sort = 0;

for(counter = 0; counter < numbers-1; counter++){

if(NUM_ARRAY[counter] > NUM_ARRAY[counter+1]){

int temp = NUM_ARRAY[counter];

NUM_ARRAY[counter] = NUM_ARRAY[counter+1];

NUM_ARRAY[counter+1] = NUM_ARRAY[counter];

sort = 1;

}

}

if(sort == 0){

break;

}

}

printf("Sorted Numbers\n");

for(counter = 0; counter < numbers; counter++){

printf("%d\n", NUM_ARRAY[counter]);

}

return 0;

}

Answer Source

You should set temp to `NUM_ARRAY[counter+1]`

instead of `NUM_ARRAY[counter]`

**Try this:**

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
int main(){
int numbers = 3;
int NUM_ARRAY[numbers];
int counter = 0;
int sort = 0;
int temp = 0;
printf("Please enter three integers\n");
for(counter = 0; counter < numbers; counter++){
scanf("%d ", &NUM_ARRAY[counter]);
}
printf("Original Numbers\n");
for(counter = 0; counter < numbers; counter++){
printf("%d\n", NUM_ARRAY[counter]);
}
while(1){
sort = 0;
for(counter = 0; counter < numbers-1; counter++){
if(NUM_ARRAY[counter] > NUM_ARRAY[counter+1]){
int temp = NUM_ARRAY[counter];
NUM_ARRAY[counter] = NUM_ARRAY[counter+1];
NUM_ARRAY[counter+1] = temp; <--- /* Since NUM_ARRAY[counter] will be set to next value in the previous step */
sort = 1;
}
}
if(sort == 0){
break;
}
}
printf("Sorted Numbers\n");
for(counter = 0; counter < numbers; counter++){
printf("%d\n", NUM_ARRAY[counter]);
}
return 0;
}
```