Write the following function that tests whether the array has four consecutive n
ID: 3546915 • Letter: W
Question
Write the following function that tests whether the array has four consecutive numbers with the same value.
bool isConsecutiveFour(const int values[], int size)
Write a test program that prompts the user to enter a series of integers and displays if the series contains four consecutive numbers with the same value. Your program should first prompt the user to enter the input size-i.e., the number of values in the series. Assume the maximum number of values is 80. Here are sample runs:
Enter the number of values: 8
Enter the values: 3 4 5 5 5 5 4 5
The list has consecutive fours
Explanation / Answer
#include <iostream>
using namespace std;
bool isConsecutiveFour( const int values[], int size )
{
int counter = 1;
int target;
//mark first value as target value
target = values[0];
for(int i = 1; i < size; i ++){
//if value is same increment the counter
if(values[i] == target){
counter++;
//check if counter is at 4
if(counter == 4){ return true;}
}
//if value is not the same change counter back to 1 and change target to new value
else{
target = values[i];
counter = 1;
}
}
//if it goes through the whole list and never returns true
return false;
}
int main()
{
int array[80];
int n;
cout << "Enter the number of values: ";
cin >> n;
cout << "Enter the values: ";
for(int i = 0; i < n ; i++){
cin >> array[i];
}
if(isConsecutiveFour(array,n)){
cout << "The list has consecutive fours." << endl;
}
else
cout << "The list does not have consecutive fours." << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.