Hi, I've been writing a bubble sort, which works entirely and calculates the sum of numbers entered, but I have run into an issue. If I enter an "endl;" command at the end of the line that displays the sum, it ruins the bubble sort. Any ideas?
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int sum, n, j, i, array[10];
sum = 0;
cout << "Please enter 10 numbers: " << endl;
for (i = 0; i < 10; i++)
{
cin >> array[i];
}
cout << endl;
cout << "Orignally entered array by the user is: " << endl;
for (j = 0; j < 10; j++)
{
sum = sum + array [j];
cout << array [j];
cout << endl;
}
for (i = 0; i < 10; i++)
{
for (j = 0; j < 10; j++)
{
if (array[j] > array[j + 1])
{
n = array[j];
array[j] = array[j + 1];
array[j + 1] = n;
}
}
}
cout << "Sorted array is: " << endl;
for (i = 0; i < 10; i++)
{
cout << array[i];
cout << endl;
}
cout << "Sum of numbers is: " << sum;
// would put "cout << endl;" here but does not work
return 0;
}
Orignally entered array by the user is:
10
90
8
7
6
5
4
3
2
1
Sorted array is:
-858993460
1
2
3
4
5
6
7
8
10
Sum of numbers is: 136Press any key to continue . . .
I run it in Debug mode and it throws the following exception: Run-Time Check Failure #2 - Stack around the variable 'array' was corrupted.
You've indexed out of bounds and corrupted memory inside your bubble sort. If j = 9, then j + 1 - 10. Your array only has 10 elements, and array[10] is actually the 11th element, which doesn't exist.
j cannot be loop until j = 9. j = 9 is too high.
Fixing the issue in the code produces this output:
Please enter 10 numbers:
10
90
8
7
6
5
4
3
2
1
Orignally entered array by the user is:
10
90
8
7
6
5
4
3
2
1
Sorted array is:
1
2
3
4
5
6
7
8
10
90
Sum of numbers is: 136Press any key to continue . . .
All you need to do is change for (j = 0; j < 10; j++)
You want to stop at the last element, which is array[9]. But j + 1 gives you 10 when j = 9 (the last loop iteration). What can you change the value of j < (NUMBER) to be to make sure you don't go out of bounds?