I'm writing a program that asks the user for a series of numbers, prints them back out, and then sorts them. I have it doing that already, it is sorted and everything, but how can I print the numbers back out ones they are sorted? For now, all I can do is print out specific numbers from the array, as you can see from my code.
@Smac89
There is no need for a nested for-loop, a single for-loop will work for this problem.
1 2 3 4 5 6 7 8 9
for (int g = 0, temp = 0; g < counter; ++g)
{
if (digits[g] > digits[g+1] && digits[g+1] != '\0')
{
temp = digits[g];
digits[g] = digits[g+1];
digits[g+1] = temp;
}
}
This code is invalid because you are trying to access an element digits[counter] (that is digits[g+1] when g == counter -1) thta has an undefined value.
EDIT: And moreover your code does not sort the array. So your code is invalid in whole.
This code is invalid because you are trying to access an element digits[counter] (that is digits[g+1] when g == counter -1) thta has an undefined value.
I specified this : && digits[g+1] != '\0' in the condition. Wouldn't that stop it from reading beyond the elements in the array?
A good code! Only I would include the header that contains the declaration of std::swap.. Ir is <utility>.
EDIT: And I would declare a named constant for the magic number 10. For example
const int N = 10;
and use this name N everywhere in the code instead of 10.
@Smac89
I specified this : && digits[g+1] != '\0' in the condition. Wouldn't that stop it from reading beyond the elements in the array?
This will not help. First of all not used elements of the array have undefined values. If you would define the array the following way
int digits[10] = {};
in this case all elements would have initial values equal to 0. But this also will not help because a user could enter all 10 elements of the array. That is the array would not have an element with value 0.