Display array in ascending order

So I'm able to display the values in ascending order, but my problem is that it's displaying all of the elements AND THEN it's displaying the values. How would I fix it so that it's just displaying the values in ascending order?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  int main() {
	const int SIZE = 100;
	int y[SIZE] = {};

	int sort;

	for (int i = 0; i <= 100;++i) {
		cout << "Enter a value between 1-100 (Press -99 to stop): " << (i + 1) << endl;
		cin >> y[i];

		if (y[i] == -99)
			break;
	}

		for (int n = 0;n < SIZE - 1; n++)
			for (int j = 0; j < SIZE - 1;j++)
				if (y[j] > y[j + 1]) {
					sort = y[j];
					y[j] = y[j + 1];
					y[j + 1] = sort;
				}

		cout << "The numbers in ascending order\n ";
		for (int p = 0; p < SIZE;p++)
			cout << y[p] << endl;
	return 0;
}
Last edited on
What do you mean by "display elements"?

Think of this: the input is
42
7
-99

Then you sort and display SIZE values of the array.
I have that part down, I guess I'm just not wording it correctly (sorry I'm just learning about arrays).
What my program does so far is prompt the user to enter values from
1-100 & display them back in ascending order using a loop & an array. So for ex if they
entered 5,10, 9,15 (-99 is used to break out of the loop), it should display 5,9,10, & 15 in that order. Instead, my program is displaying a ton of zeros & then the numbers in ascending order. How do I fix this?
Last edited on
How do I fix this?
It could sound funny, but there’s nothing to fix :-) Your program works correctly, printing all values in ascending order.

What keskiverto was pointing out is (I think):
- you create an array of SIZE elements
- you set all of them to 0.
- you ask the user for values from 1 to 100
- but 1 is greater then 0
- it means the littlest value the user is expected to enter is anyway greater then what’s already there inside the array
- then you sort the array in ascending order, so when you print it...

If you want to change your program behaviour you need to know...
Yes. (I've failed to post twice now. Lets see if this one comes through.)

You ask for some values, but you don't care how many you actually get.
Whatever the input, you always sort all 100 values and always print all 100 values.

If you do want to sort and show only the values that the user gives, then you have to count them and use that count.


There are two unrelated details:
1. Line 7. How many times does this loop repeat (if no -99 is in input)?
You can get an out-of-range error with that. Memory corruption. Undefined behaviour.
2. You do store the -99 into the array. This looks like a logical error.
Topic archived. No new replies allowed.