Duong Luong Binh Duong Luong Binh -4 years ago 53
C Question

Is it Code Block error?

I have an assignment which required me to sort any random numbers. The code below is weird. The reason is after clicking running the program, if I type 5 at the beginning, it does not work perfectly, however, it works correctly with other numbers. Please help me to fix this error. I also attached the pictures to prove what I said above.

Image when enter number 5

Image when enter number 10

#include <stdio.h>
int main(){
int howmany,i,temp,swap;

printf("Enter how many numbers you want to sort: \n");
scanf(" %d",&howmany);

int number[howmany];

printf("*** The original numbers *** \n");

for (i=0;i<howmany-1 ;i++){
number[i]=(rand()% 25)+1;
printf("Random number is: %d\n",number[i]);
}

while(1){
swap = 0;
for (i=0;i<howmany-1;i++){
if(number[i]>number[i+1]){
temp = number[i];
number[i]=number[i+1];
number[i+1] = temp;
swap = 1;
}

}
if (swap == 0){
break;
}
}
printf("*** The sorted numbers ***\n");
for (i=0;i<howmany-1;i++){
printf("The sorted number: %d\n",number[i]);


}


}

Answer Source

The issue is because you are reading and printing one less than the actual size of the array. So the last entry of the array will have some junk value which you don't know. But while sorting you are using it and it gets sorted. Sometimes the junk value is lower than the other random values and it gets printed.

I have made the fix. Please check all the for loops.

#include <stdio.h>
int main(){
int howmany,i,temp,swap;

printf("Enter how many numbers you want to sort: \n");
scanf(" %d",&howmany);

int number[howmany];

printf("*** The original numbers *** \n");

for (i=0;i<howmany ;i++){ //Read howmany values and print
    number[i]=(rand()% 25)+1;
    printf("Random number is: %d\n",number[i]);
}

while(1){
    swap = 0;
    for (i=0;i<howmany-1;i++){
        if(number[i]>number[i+1]){
            temp = number[i];
            number[i]=number[i+1];
            number[i+1] = temp;
            swap = 1;
            }

    }
    if (swap == 0){
        break;
    }
}
printf("*** The sorted numbers ***\n");
for (i=0;i<howmany;i++){ //Print howmany values 
    printf("The sorted number: %d\n",number[i]);


}


}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download