Specification: Assume that two arrays, x and y, are both fifty-element arrays and that they contain double values. This function is supposed to switch the lowest x value with the lowest y value; that is, the lowest value in x is switched with the lowest value in y.

```
void Switcher(double x[], double y[])
{
double low_x = 0, low_y = 0;
int i, i_x, i_y;
for(i = 0; i < 50; ++ i)
{
if(x[i] < low_x)
low_x = x[i]; //find low x
i_x = i; //remember x index
if(y[i] < low_y)
low_y = y[i]; //find low y
i_y = i; //remember y index
}
y[i_y] = low_x;
x[i_x] = low_y;
}
```

This routine initially sets the low values to 0.0, and we do not know the range of values for these arrays. Chances are, unless the arrays contain all negative values, we will not find the correct low values.

A second problem is due to the fact that both if statements do not contain { }, both assignment statements into i_x and i_y will be performed at each pass of the loop. The resulting action is that the last two values always will be switched.

There are three corrections. First set the initial low values to the first element in the arrays, set the initial index values to 0, and use the { } with the if statements.

```
double low_x = x[0], low_y = y[0];
int i, i_x = 0, i_y = 0;

for(i = 0; i < 50; ++ i)
{
if ( x[i] < low_x)
{
low_x = x[i];
i_x = i;
}
// same for the y array
}
```
After the for loop, we must then assign the low values into the opposing arrays, like this:

x[i_x] = low_y;
y[i_y] = low_x;

Computer Science & Information Technology

You might also like to view...

A primary key field that uses two or more fields is known as a __________.

a. simple primary key b. composite primary key c. foreign key d. candidate key

Computer Science & Information Technology

C++ stores an array in adjacent memory locations. In what array position (counting from the start) will the element myArray [7][21] be stored in, if myArray has 10 rows and 50 columns?

What will be an ideal response?

Computer Science & Information Technology