Consider the following function. Complete the function that does the following:
ID: 3740674 • Letter: C
Question
Consider the following function. Complete the function that does the following:
(a) Take three arguments, int array, int as the length of the array, and int *max.
(b) Find the maximum value and the minimum value in the array.
(c) The pointer max points to the maximum value.
(d) Return the pointer that points to the minimum value.
int * findMinAndMax(int a[ ], int length, int * max) {
int maxValue = a[0], minValue = a[0];
int maxIdx = 0, minIdx = 0;
for (int idx =1; idx < length; idx++) {
if (a[idx] > maxValue) {
maxValue = a[idx];
maxIdx = idx;
}
if (a[idx] < minValue) {
minValue = a[idx];
minIdx = idx;
}
}
}
Consider the above function. Declare an integer array called myArray of length 5. Initialize myArray to 4, 1, -5, 3, 5, in sequence. Declare two pointers ptrMin and ptrMax, both pointing to integer. Call the above function findMinAndMax so that the pointer ptrMin points the the minimum value in the array and the pointer ptrMax points to the maximum value in the array.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
int *findMinAndMax(int a[], int length, int *max);
int main()
{
int a[] = {4,1,-5,3,5};
int *max = (int*)malloc(sizeof(int));
int *min = findMinAndMax(a,5,max);
printf("%d %d ", min,max);
printf("%d %d ", *min,*max);
return 0;
}
int *findMinAndMax(int a[], int length, int *max){
int *min;
min = a;
*max = *a;
int i=0;
for ( i = 0; i < length ; ++i)
{
if(*min > a[i]){
min = (a+i);
}
if(*max < a[i]){
*max = *(a+i);
}
}
return min;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.