Hubert Jo - 4 months ago 30

C++ Question

I'm new to c++ and I need some help with a for loop algorithm in my doubleUp function. The purpose of the doubleUp function is if an array has the same consecutive values, then each number would be doubled. An example is if an array has the elements of 4, 4, 4, and 4. The new array would be 8, 8, 8, 8 by using the doubleUp function. Thanks again guys! :D

`#include <iostream>`

using namespace std;

void collectScores(double scores[], int SIZE);

void printScores(double scores[], int stopPlace);

void doubleUp(double scores[], int SIZE);

void collectScores(double scores[], int SIZE)

{

for (int n = 0; n < SIZE; n++)

{

cout << "Please enter a value for element " << (n) << " : ";

cin >> scores[n];

}

cout << endl;

}

void printScores(double scores[], int stopPlace)

{

for (int n = 0; n < stopPlace; n++)

{

cout << "The value of element " << (n) << " : " << scores[n] << endl;

}

}

void doubleUp(double scores[], int SIZE)

{

for (int n = 0; n < SIZE; n++)

{

if (scores[n] == scores[n + 1])

{

scores[n] *= 2;

}

}

}

int main()

{

double r;

const int SIZE = 4;

double scores[SIZE];

collectScores(scores, SIZE);

printScores(scores, SIZE);

cout << endl;

doubleUp(scores, SIZE);

printScores(scores, SIZE);

system("pause");

return 0;

}

Answer

Besides that you were missing an edge case at the end there is a bigger problem. Since you're looking ahead, in one direction, for doubles, this means that you will miss doubling the last element of *every* island of adjacent equal numbers. In my code below I have added a single state variable called `isDouble`

which addresses the problem.

```
void doubleUp(double scores[], int SIZE)
{
if (SIZE < 2) return; // 0 or 1 element just return
bool isDouble = false;
for (int n = 1; n < SIZE; n++)
{
if (scores[n] == scores[n - 1])
{
isDouble = true;
scores[n - 1] = 2*scores[n - 1];
}
else if (isDouble)
{
isDouble = false;
scores[n - 1] = 2*scores[n - 1];
}
}
// edge case: possibly double the last element in the array
// if it be identical to the second to last element
if (isDouble) scores[SIZE-1] = 2*scores[SIZE-1];
}
```