Pls specify which is libmaxarray.h and libmaxarray.c Q1) Write a function that t
ID: 3828960 • Letter: P
Question
Pls specify which is libmaxarray.h and libmaxarray.c
Q1) Write a function that takes an array and its size as inputs, and then finds (i) the maximum value in the array and (ii) the index of the maximum value’s first occurrence. For example, if the array contains the values (2, 3, 8, 6, 8), then the maximum element of the array will be 8, and the index of the first occurrence of 8 is 2 (indices start from 0). To find the maximum element of the array and the index, you must make a function with the following prototype:
Note that this function takes an integer array as its first argument, the array’s size as its second argument, and two integer pointer arguments. The pointers maxValPtr and maxIdxPtr point to integer variables in the caller. After calling maxElem, the caller’s integer variables should be updated with the maximum value in the array and the index of the first occurrence of the maximum value in the array, respectively. This problem demonstrates that variables defined in the caller can be changed in callee functions by using pointers.
Note: You must write your function prototype in a header file named libmaxarray.h and you must write your function definition in a source file named libmaxarray.c. We are pro- viding you the main source file maxarray.c, which you can use to test your function. Do not change anything in maxarray.c.
(maxarray.c)
#include<stdio.h>
#include<stdlib.h>
#include "libmaxarray.h"
void getArr(int arr[], int arrSize);
int main(void)
{
int len, i, maxVal, maxIdx;
int *arrayIn;
/* get input */
printf("Input the array size: ");
scanf("%d", &len);
if (len < 1) {
printf("Array size must be 1 or larger. ");
return 0;
}
/* dynamic memory allocation */
arrayIn = (int*) malloc(len * sizeof(int));
/* read array from stdin */
getArr(arrayIn, len);
/* determine maxVal and maxIdx */
maxElem(arrayIn, len, &maxVal, &maxIdx);
/* print result */
printf("The maximum element of the array is %d. ", maxVal);
printf("The index of the first occurence of the maximum element is %d. ", maxIdx);
/* free dynamically allocated memory */
free(arrayIn);
return 0;
}
void getArr(int arr[], int arrSize)
{
int i;
if (arrSize == 1)
printf("Input INT1: ");
else if (arrSize == 2)
printf("Input INT1 INT2: ");
else
printf("Input INT1 INT2 ... INT%d: ", arrSize);
for (i = 0; i < arrSize; i++) {
scanf("%d", &arr[i]);
}
}
Explanation / Answer
Hi, Please find my implementation of required method.
Since you have not posted libmaxarray.h file, so i could not test.
void maxElem(int array[], int size, int *maxValPtr, int *maxIdxPtr){
int max = array[0]; // initializing max with first element of array
int index = 0;
for(int i=1; i<size; i++){
if(max < array[i]){ // if current element of array is greater than max
max = array[i];
index = i;
}
}
*maxValPtr = max;
*maxIdxPtr = index;
}