Write a function to find the highest and lowest values in an array of numbers us
ID: 3641214 • Letter: W
Question
Write a function to find the highest and lowest values in an array of numbers using pointers (rather than subscripts).Also, write a main program to test this function by passing a pointer to the array, the number of elements in the array, a pointer for the highest value and a pointer for the lowest value.
that is what i have so far :
#include <iostream>
using namespace std;
void findHighLow(int* a, int size, int* high, int* low){
int max = 0, min = 0;
for(int i =0; i < size; i++){
if( *(a + i) > max)
max = i;
if(*(a + i) < min)
min = i;
}
*high = *(a +max);
*low = *(a + min);
}
int main()
{
int a[] = {3,4,5,2,1,0,10,6};
int x = 0;
int y = 0;
findHighLow(a, 8, &x, &y);
cout << "Max: " << x << endl;
cout << "Min: " << y << endl;
cin.get();
}
the thing is for some reason it does not give the right highest and lowest value, for some reason, it gives me the first one and the last one my output after i changed the numbers in the array to {68,4,5,2,1,8,1,6} is : max: 6 min: 68.
Where the problem is coming from ?
Explanation / Answer
void findHighLow(int* a, int size, int* high, int* low) {
int max = 0, min = 0; //index, should change name to minIndex, maxIndex
for(int i = 0; i < size; i++) {
//if(*(a + i) > max) //here you are comparing the actual value with the index.
if(*(a + i) > *(a + max)) //You should change to this
max = i;
//if(*(a + i) < min)
if(*(a + i) < *(a + min)) //here, too
min = i;
}
*high = *(a + max);
*low = *(a + min);
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.