227k views
0 votes
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.

1 Answer

3 votes

Answer:

Following is the source code required:

int entry_1 ,entry_2 = -1, consecutive_duplicates = 0;

do {

cin >> entry_1;

if ( entry_2 == -1)

{

entry_2 = entry_1;

}else

{

if ( entry_2 == entry_1 )

consecutive_duplicates++;

else

entry_2 = entry_1;

}

}

while(entry_1 > 0 );

cout << consecutive_duplicates;

Step-by-step explanation:

Following is the explanation for given code:

  • 3 integers are declared as entry_1, entry_2 and consecutive_duplicates.
  • entry_2 = -1 (it will tell that the integers are non-zero)
  • user will enter the value for entry_1
  • The loop will be applied which will check for the value of entry_2. If entry_2 = -1, the value of entry_1 will be stored in entry_2 else it the value of entry_2 is already equal to entry_1, the integer consecutive_duplicate in increased by one.
  • Now the value of entry_1 is stored in entry_2 , so that next entity might be checked.
  • In the end, while the entry_1 is greater than zero (unless the last (negative)element of array is reached), print the integer consecutive_duplicates.

i hope it will help you!

User ILovemyPoncho
by
7.2k points