bubble sort is adding its own number

when i run the program the first int that is stored in the array keeps changing to -858993460. please help thank you

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
using namespace std;

int main()
{
	int i;
	int j;

	int testScore[5];
	int count;

	for (count = 0; count < 5; count++)
	{
		cout<< "Enter the 5 test scores "
			<< (count + 1 ) << ":";
		cin >> testScore[count];
	}

	cout << "the test scores you entered are:" << endl;
	for (count = 0; count < 5; count++)
	{
		cout<< " " <<  testScore[count];
		cout << endl;
	}

	for(i = 0; i<= 4; i++)
	{
		for (j = i+1; j<= 5; j++)
		{
			int hold = 0;

			if(testScore[i] > testScore[j])
			{
				hold = testScore[i];
				testScore[i] = testScore[j];
				testScore[j] = hold;
			}
		}
	}

	cout << "The test scores from lowest to highest are:" << endl;

	for (count = 0; count < 5; count++)
	{
		cout<< " " <<  testScore[count];
		cout << endl;
	}

	system ("pause");
	
0}
Valid elements are (and as you notice there's five of them):
testScore[0] testScore[1] testScore[2] testScore[3] testScore[4].

There is no element testScore[5] and yet your j eventually reaches 5.

This is called going out of bounds, and it is bad. Sometimes the program crashes, other times you get garbage.

26
27
28
29
	for(i = 0; i< 4; i++) // go up to 3
	{
		for (j = i+1; j< 5; j++) // go up to 4
		{
Last edited on
Topic archived. No new replies allowed.