SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Arrays
Exercise:
Self-test Exercises
Question:8 | ISBN:9780321531346 | Edition: 7

Question

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.";

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

The bug in the provided code is the condition inside the for loop where it checks a[index] > a[index + 1].

  • This condition will cause an out-of-bounds access when index reaches the last element of the array (index = 9), as it tries to access a[9 + 1], which is beyond the array bounds. 
  • To fix this bug, we need to modify the condition to ensure that the loop only iterates up to the second-to-last element of the array.
  • Here's the corrected code:
                  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.";
    }
}
  • In the corrected code, the condition in the 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]).
  • This prevents the out-of-bounds access when accessing a[index + 1].
0 0

Discussions

Post the discussion to improve the above solution.