GrantaOmega GrantaOmega - 2 months ago 1337
C++ Question

How to write loop that ends in negative number (MyProgrammingLab 11138)

Consider this data sequence: "3 11 5 5 5 2 4 6 6 7 3 -8". Any value that is the same as the immediately preceding value is considered a CONSECUTIVE DUPLICATE. In this example, there are three such consecutive duplicates: the 2nd and 3rd 5s and the second 6. Note that the last 3 is not a consecutive duplicate because it was preceded by a 7.
Write some code that uses a loop to read such a sequence of non-negative integers , terminated by a negative number. When the code exits the loop it should print the number of consecutive duplicates encountered. In the above case, that value would be 3.

This is a question from MyProgrammingLab exercise 11138. This needs to be written in C++, and we are not allowed to use any arrays yet. Thank you so much for your help. I really appreciate it.

Here is what I have so far:

int firstNumber;
int secondNumber;
int duplicates;

secondNumber = duplicates = 0;
cin >> firstNumber;

while (firstNumber > -1 && secondNumber > -1)
{
secondNumber
if (firstNumber == secondNumber)
{
duplicates++
}
firstNumber = secondNumber;
}

cout << duplicates;

Answer

You are almost there. Just a little change is needed.

cin >> firstNumber;
while ( firstNumber > -1 ) { // only firstNumber alone can handle this.
    cin >> secondNumber;
    if (firstNumber == secondNumber)
        duplicates++;
    else
        firstNumber = secondNumber;
}

EDIT - As suggested by Bob__ a single one cin can also solve this.

int firstNumber,secondNumber = -1, duplicates = 0;
do {
    cin >> firstNumber;
    if ( secondNumber == -1) {
        secondNumber = firstNumber;
    }else {
        if ( secondNumber == firstNumber ) 
            duplicates++;
        else
            secondNumber = firstNumber;
    }
} while(firstNumber > 0 );