Obtaining the maximum element from an array

The function that deduces the maximum element from the array is never called hence I am unable to obtain the maximum element. What is happening?
Below is the code.

int Array [] = {};
int i;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

int maximum (int Array[], int n) {
  int max = 0;
  Serial.print("in the maximum function");

  for (int i = 0; i < n; i++ ) {
		if ( Array[i] > max)	{
			max = Array[i];
		
    Serial.print("The max value is: ");
    Serial.println(max);
    }
	}
}

void loop() {
  // put your main code here, to run repeatedly:
//   int Array[] = {};
  for (int i = 0; i < 10; i++) {
    Array [i];
    int num = random (0,9);
    Array [i] = {num};
    Serial.print(Array[i]);
    Serial.print(",");
    delay(1500);   
  }

  int maximum (Array[i], 10);

  Serial.println("Full Array");
  delay(3000);
}

hi!
this won't make wha tyou want.
do you know what will be the "i" you transfer to the function?

maybe something like this :

maximum(Array[],10); without the int (you are declaring a diiferent function with same name with the "int" before)

EDIT: a cleaner solution should be to pass the first element (Array[0]) and the size of this array (with sizeof() ) as arguments for your function "maximum".

How many elements?

You could start with a function that accepts an array (or pointer to its first element) and its size separately.

int maximum_(int const arr[], size_t const n) {
  // Note that `arr` needs to have at least one element.
  int max_ {arr[0]};
  for (size_t i {1}; i < n; ++i) {
    if (arr[i] > max_) {
      max_ = arr[i];
    }
  }
  return max_;
}

If, additionally, you want to be able to deduce the size of the array automatically, you can add the following function.

template <size_t n> int maximum(int const (&arr)[n]) {
  return maximum_(arr, n);
}

Alternatlvely, you could use the classical approach to deduce the size of the array.

maximum_(arr, sizeof(arr) / sizeof(arr[0]));

Example:

void setup() {
  Serial.begin(9600);

  int arr[] {12, 3, 4, 2, 19, 21, 8, 1};
  Serial.println(maximum(arr));                                 // Prints "21".
  Serial.println(maximum_(arr, sizeof(arr) / sizeof(arr[0])));  // Prints "21".
}

[edit]

To create an array containing random values, you first need to create the array of the desired size. Only then can you set its elements.

int arr[10] {};  // Notice the size (10) between the brackets.
for (int& el: arr) {
  el = random(10);  // Set the element to a value between 0 and 9.
}
1 Like

It could be done with qsort.

Your code has a number of small and not-so-small errors. But the intent is clear, and the logic is sound.

You have already received some various advices. Food for thought no doubt, if not now then someday.

But today, here's your sketch, as close as I could leave it as I found it, with the errors changed into not-errors using only things it seems you know or are trying to learn about.

I will make you read through it, see anything marked "//...", a comment I put in where I had to make those adjustments.


You can see it run in the simulator--> CLICK ME.


// https://wokwi.com/projects/359387026908041217
// https://forum.arduino.cc/t/obtaining-the-maximum-element-from-an-array/1102930

int Array [10];  //... you need to, at some point, make room for N elements
int i;

void setup() {
  Serial.begin(9600);
}

//... the arguments can have any names you'd like
int maximum (int anArray[], int n) {
  int max = 0;

  Serial.println("in the maximum function:");

  for (int i = 0; i < n; i++ ) {
		if ( anArray[i] > max)	{
			max = anArray[i];
		
      Serial.print("    The (new) max value is: ");
      Serial.println(max);
    }
	}
//... you promised to return ann int, but failed to
  return max;
}

void loop() {
  for (int i = 0; i < 10; i++) {
//... statement does... absolutely nothing
//    Array [i];

//... check random - the upper limit is not returned!
    int num = random (0,10);  //... random number 0..9 inclusive

    Array [i] = {num};
    Serial.print(Array[i]);
    Serial.print(",");
    delay(150);   //... life to short!
  }

//... I moved this print statement. Sue me.
  Serial.println("       Full Array ");

//... this is a declaration. it does not execute any code
//  int maximum (Array, 10);
//
// you want to actually call the function you wrote, and assign the returned value value.

  int theMaximum = maximum(Array, 10);

  Serial.print("         maximum from function call ");
  Serial.println(theMaximum);

  delay(300);  //... life too short!
}

It's fun to watch as it usually ends up finding a '9' to report out as the maximum. What are the odds? If you know about probability, you can calculate it. If not, you are very close to being able to run this for several thousands of times and count how often every 0..9 shows up...

HTH and welcome to the community!

a7

Remember also, that your maximum number could be negative :wink:

(In that case, initialise max to the first element, and iterate over the rest of the elements)

1 Like

Indeed. I did rely on the way the OP stuffs the array.

I like the use of the value of the first element for max (and min if you happen to be intereseted in that, too).

I don't know if that ever occurred to me; I do know I've said things like

   int min = 32767;
   int max = -32768;

which is not so nice. And I don't know what I would put if it were an array of float data.

a7

Into memory they don't have?

No, that was one of the errors I pointed out in the adjusted code.

I did want to leave the sketch as close to the OP's as possible, so didn't a lot of things I might have also. Done.

a7

  • the posted code doesn't compile, so can't be tested
  • the following is a more like declaration of a function, but still a invalid statement

it should be invoked with reference to the array, not a single element of the array

maximum (Array, 10);

and with maximum() corrected to return the maximum value, that return value is ignored. so maybe

Serial.println (maximum (Array, 10));
  • the size of Array [] is zero. possibly
    int Array [10];

consider

int Array [10] = {};
int i;

void setup() {
    Serial.begin(9600);
}

int maximum (int Array[], int n) {
    int max = Array [0];
    for (int i = 0; i < n; i++ ) {
        if ( Array[i] > max){
            max = Array[i];
        }
    }
    return max;
}

void loop() {
    // put your main code here, to run repeatedly:
    //   int Array[] = {};
    for (int i = 0; i < 10; i++) {
        int num = random (0,9);
        Array [i] = {num};
        Serial.print(" ");
        Serial.print(Array[i]);
    }
    Serial.println ();

    Serial.print   ("max ");
    Serial.println (maximum (Array, 10));

    delay(1000);
}

Wouldn't it be nice to have some kind of predefined values that give the limits of different types? ... Wait a minute!
https://en.cppreference.com/w/c/types/limits

#include <limits.h>
#include <float.h>

   int min = INT_MAX;
   int max = INT_MIN;
   float fmin = FLT_MAX;
   float fmax = -FLT_MAX; // fixed; was FLT_MIN
2 Likes

isn't this a place for a template?

@oqibidipo Thanks for that, I see a few constants I wasn't aware of, or had forgotten, that should replace constants I've created in my code. Useful, indeed.

Note that FLT_MIN is the smallest possible positive floatvalue. That means it's the smallest float greater than zero ... so like 2^(-126) or something.

I guess if you want the smallest negative float value it would be -FLT_MAX.

thank you all guys..... I solved it now. All your comments were handy.
A few things I should have done better in posting this question;

  1. Explain precisely what I wanted to do even if the code seemed fairly straightforward.
  2. Add enough comments within my code to explain it further.

I think my problem was how I was passing the arguments into the maximum function. I wasn't passing the arguments rightly. Also, I wasn't returning anything after the maximum function ran.

Worked very well. You did a very good job understanding my code. After reading the code again, I realized as straightforward as it was, I needed to add comments and explain what I was doing.

But your code really makes sense and does precisely what I was looking to do. My problem, I figured, was that I wasn't passing the right arguments to the Maximum function and I wasn't returning anything from the function.

Thank you for the help and thanks to the community.

Is there a way to add timestamps to these elements? Say, you want to ascertain when an element gets added to the array.
So the thing is, I have a sensor suit that spits data periodically. I put the data into an array with timestamps to show at what time the data was stored in the array. The maximum function then tells me what the maximum reading from the sensor was after the array gets full.
If this issue has already been delt with, I would like to see it if not, I would please need some help.

Assuming you mean a parallel array with an element storing the time for every sample or reading or whatever…

...then while looking for the max in the readings array, record not only the new max, but the index where you found it.

Then the time the max happened will be at that index in the timings array.

Parallel arrays can also be expressed by using struct variables, here you would need an array of structs.

But parallel arrays for now if you don't need or want to look into structs.

a7

makes sense. Thank you