rebbailey rebbailey - 2 months ago 7
C Question

For-loop not printing array

I have successfully sorted the

values
, but when trying to print them with the for-loop or printf at the end, the program does nothing.

int main(void){
int values[] = {23,19,1};
int size = 3;
int counter = 0;
int i;
int holder;

for(i = 0; i < size; i++){
counter = 0;
if(values[i] > values[i + 1]){
holder = values[i];
values[i] = values[i + 1];
values[i + 1] = holder;
counter = 1;
printf("index: %i = %i, index: %i = %i\n", i, values[i], i + 1, values[i + 1]);
printf("Sorting..\n");
}
if((i + 2) == size){
if(counter == 0){
printf("The array is sorted! %i, %i, %i\n", values[0], values[1], values[2]);
return true;
break;
}
else {
i = -1;
}
}
}

printf("%i\n", values[0]);

for(i = 0; i < size; i++){
printf("%i\n", values[i]);
}
return 0;
}


The programs output is:

index: 0 = 19, index: 1 = 23
Sorting..
index: 1 = 1, index: 2 = 23
Sorting..
index: 0 = 1, index: 1 = 19
Sorting..
The array is sorted! 1, 19, 23

Answer

Your return true after the array is sorted is popping out of the main function, so the print code at the bottom is never reached.