Write the following functions in the C++ program and call each of them from main
ID: 3686821 • Letter: W
Question
Write the following functions in the C++ program and call each of them from main() with the values given in the questions, to verify the correctness of your code.
int findMax(const int ar[], int size);
This function receives an array of int's and its size, and returns the largest element value stored in the array.
- Call the function with {5,1,9,3,4} and ensure you get the correct value.
int findMaxIndex(const int ar[], int size);
This function receives an array of int's and its size, and returns the INDEX where the largest element value is found in the array.
- Call the function with {5,1,9,3,4} and ensure you get the correct values -- 2.
void copyArray(const int from[], int to[], int size12);
This function receives two arrays 'from' and 'to' and their size (assumed to be the same length), and copies (and overwriting) the elements in the 'from' array into the 'to' array.
- Call the function with {1, 2, 3, 4, 5} for 'from' and an empty array of size 6.
bool isUnique(const int ar[], int size);
This function receives an int array and its size, and returns true if the elements in the parameter array are all unique (i.e., no duplicates) or false otherwise. Note that you will need a nested loop.
Call the function with {9, 1, 3, 4, 0, 2} (for which the function should return false).
Explanation / Answer
#include <iostream>
using namespace std;
const int n[]={5,1,9,3,4,1};
int findMax(const int ar[], int size)
{
int max=0;
for(int i=0;i<size;i++)
{
if(max<ar[i])
max=ar[i];
}
return max;
}
int findMaxIndex(const int ar[], int size)
{
int max=0,maxindex=-1;
for(int i=0;i<size;i++)
{
if(max<ar[i])
{
max=ar[i];
maxindex=i;
}
}
return maxindex;
}
void copyArray(const int from[], int to[], int size12)
{
for(int i=0;i<size12;i++)
{
to[i]=from[i];
}
}
bool isUnique(const int ar[], int size)
{
for(int i=0;i<size-1;i++)
{
for(int j=i+1;j<size;j++)
{
if(ar[i]==ar[j])
{
return false;
}
}
}
return true;
}
int main()
{
int to[10];
cout << findMax(n,6)<< endl;
cout << findMaxIndex(n,6)<< endl;
copyArray(n,to,6);
if(isUnique(n,6))
cout<<"Array is unique";
else
cout<<"Duplicates exist";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.