Suppose we expect the elements of the array a to be ordered so that
a[0] ≤ a[1] ≤ a[2]≤ ...
However, to be safe we want our program to test the array and issue a
warning in case it turns out that some elements are out of order. The
following code is supposed to output such a warning, but it contains a
bug. What is it?
double a[10];
<Some code to fill the array a goes here.>
for (int index = 0; index < 10; index++)
if (a[index] > a[index + 1])
cout << "Array elements " << index << " and "
<< (index + 1) << " are out of order.";
The bug in the provided code is the condition inside the for
loop where it checks a[index] > a[index + 1]
.
index
reaches the last element of the array (index = 9
), as it tries to access a[9 + 1]
, which is beyond the array bounds.
double a[10];
// Some code to fill the array a goes here.
for (int index = 0; index < 9; index++)
{
if (a[index] > a[index + 1])
{
cout << "Array elements " << index << " and " << (index + 1) << " are out of order.";
}
}
for
loop is changed to index < 9
, which ensures that the loop only iterates up to the second-to-last element of the array (a[8]
).a[index + 1]
.