In: Computer Science
Im trying to create a function in C where it takes an array and size and returns the largest absolute value in the array (either negative or positive) using only stdio.h. Any help would be greatly appreciated!
Ex: if the array is { -2.5, -10.1, 5.2, 7.0}, it should return -10.1
Ex: if the array is {5.1, 2.3, 4.9, 1.0}, it should return 5.1.
double getMaxAbsolute(double array[], int size)
{
double max = array[0];
double abs[size];
for (int i = 0; i < size; i++) {
if ( array[i] >=
0){
abs[i] = array[i];
}
else if (abs[i] <
0){
abs[i] = -
array[i];
}
if (abs[i] > max)
{
max = array[i];
}
}
return max;
}
#include <stdio.h>
double getMaxAbsolute(double array[], int size)
{
double maximum = array[0];
double actual_value = maximum;
if(maximum < 0)
maximum = maximum*-1;
int i;
for(i=1; i<size; i++)
{
if(array[i] < 0 && array[i]*-1 > maximum)
{
actual_value = array[i];
maximum = array[i]*-1;
}
else if(array[i] >= 0 && array[i] > maximum)
{
actual_value = array[i];
maximum = array[i];
}
}
return actual_value;
}
int main(void) {
double a[] = { -2.5, -10.1, 5.2, 7.0};
printf("%lf\n", getMaxAbsolute(a, 4));
double b[] = {5.1, 2.3, 4.9, 1.0};
printf("%lf\n", getMaxAbsolute(b, 4));
return 0;
}
/*OUTPUT
-10.100000
5.100000
*/
// Hit the thumbs up if you are fine with the answer. Happy Learning!