Write array functions that carry out the following tasks for a passed array of i
ID: 3759438 • Letter: W
Question
Write array functions that carry out the following tasks for a passed array of integers:
isSortedIncreasing: Returns true if the array is currently sorted in increasing order.
isSortedDecreasing: Returns true if the array is currently sorted in decreasing order.
hasAdjecentDuplicates: Returns true if the array contains two adjacent duplicate values.
hasDuplicates: Returns true if the array contains duplicate values (which need not be adjacent).
Please remember that, for all of the above functions, you must specify both the array reference and the size of the array, e.g.:
bool hasDuplicates( int values[], int size )
Provide a program that tests your functions via a loop construct for acquiring testing data for an array of six elements (please note that the array functions must be written to handle any number of elements).
Example run (with user input indicated with bold italics):
Enter integer #0: 1
Enter integer #1: 2
Enter integer #2: 2
Enter integer #3: 4
Enter integer #4: 6
Enter integer #5: 7
The data are increasing.
The data are not decreasing.
The data has adjacent duplicates.
The data has duplicates.
Press any key to continue . . .
Explanation / Answer
#include<iostream>
#include <map>
using namespace std;
bool isIncreasing(int arr[],int size)
{
bool result = true;
for(int i=1;i<size;i++)
if(arr[i]<arr[i-1])
result = false;
return result;
}
bool isDecreasing(int arr[],int size)
{
bool result = true;
for(int i=1;i<size;i++)
if(arr[i]>arr[i-1])
result = false;
return result;
}
bool hasDuplicate(int arr[],int size)
{
map<int,int> duplicate;
bool result = false;
for(int i=0;i<size;i++)
{
if(duplicate[arr[i]]!=0)
result = true;
else
duplicate[arr[i]] = 1;
}
return result;
}
bool hasAdjacentDuplicate(int arr[],int size)
{
bool result = false;
for(int i=0;i<size-1;i++)
{
if(arr[i] == arr[i+1])
result = true;
}
return result;
}
int main()
{
int arr[6];
cout << "Inputting 6 elements : ";
for(int i=0;i<6;i++)
{
cout << "Input integer number " << i+1 << " : ";
cin >> arr[i];
}
if(isIncreasing(arr, 6))
cout << "The data are increasing." << endl;
else
cout << "The data are not increasing." << endl;
if(isDecreasing(arr, 6))
cout << "The data are decreasing." << endl;
else
cout << "The data are not decreasing." << endl;
if(hasAdjacentDuplicate(arr, 6))
cout << "The data has adjacent duplicates." << endl;
else
cout << "The data has no adjacent duplicates." << endl;
if(hasDuplicate(arr, 6))
cout << "The data has duplicates." << endl;
else
cout << "The data has no duplicates." << endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.