What the code does:
My problem: when the sorted numbers are printed out, it also adds the 0 (zero), which only purpose is to finish the task and not be added to the list of numbers entered by the person. For example if I add: 4,5,8,1,3,1,10 ("0" to finish). The printing result will be: 0, 1, 1, 3, 4, 5, 8, 10.
I'm new to C (worked with it for only about 2 weeks). So far I've tried changing " i " to 1 in this for-loop. However, all it does is to basically shift everything one step (?). Causing the 0 only to go from being first to last: 1, 1, 3, 4, 5, 8, 10, 0.
> //Bubble sort:
> for (int i = 0; i < inputNumber; i++)
I assume using free() will only work when you're looking to free all the memory stored and not one particular number? Any help is appreciated. Further, yes this is a work assignment :).
Here's the code:
int main()
{
int nr = 1;
int temp;
int *numberStore = malloc(sizeof(int));
int inputNumber = 0;
while (nr != 0)
{
printf("Add numbers to be stored (finish by entering 0): ");
scanf("%d", &nr);
printf("\n");
numberStore[inputNumber] = nr;
inputNumber++;
numberStore = realloc(numberStore, (inputNumber + 1) * sizeof(int));
}
//Bubble sort:
for (int i = 0; i < inputNumber; i++)
{
for (int j = 0; j < (inputNumber - i - 1); j++)
{
if (numberStore[j] > numberStore[j + 1])
{
temp = numberStore[j];
numberStore[j] = numberStore[j + 1];
numberStore[j + 1] = temp;
}
}
}
//Prints the stored numbers in ascending order:
for (int i = 0; i < inputNumber; i++)
{
printf("%d\n", numberStore[i]);
}
return 0;
}
Just simply don't add 0
to your data
while (nr != 0)
{
printf("Add numbers to be stored (finish by entering 0): ");
scanf("%d", &nr);
printf("\n");
if (nr != 0) // only add if not 0
{
numberStore[inputNumber] = nr;
inputNumber++;
numberStore = realloc(numberStore, (inputNumber + 1) * sizeof(int));
}
}
Or, same idea, slightly more compact: if (nr == 0) break;