Jump to content

C - Finding the minimum value in an array


barrytone
 Share

Recommended Posts

I've hit a bit of a problem with a function I wrote in C.

I needed a function to find the minimum value in an array of integers, without knowing it's size. I started with this:

int minvalue(int iar[]) {



    int ret = iar[0], count=0;



    while (iar[count]) {



        if (iar[count] < ret) {

            ret = iar[count];

        }

    count++;

    }



return(ret);

}

But I then realised I would hit problems if the array contained a '0' half way though, and the loop would stop executing.

So then I tried this:

int minvalue(int iar[]) {



    int ret = iar[0], count=0;

    int size = sizeof(iar)/4;



    while (count < size) {



        if (iar[count] < ret) {

            ret = iar[count];

        }

    count++;

    }



return(ret);

}

I'm sure it's a feature and not a bug, but the sizeof() function doesn't seem to be returning the size of the array that's fed to the function. It just returns '4' no matter what.

If anyone could help me out and explain what it is I have to do to make this work, or has a neat little function of their own that they wouldn't mind sharing, that would be fantastic :)

Many thanks.

Oh, and yes: I am a C newbie.

Link to comment
Share on other sites

The sizeof function returns the size of the element you pass it. In this case you're passing it a pointer, which is 32 bits. :)

The way you deal with arrays is that they're either fixed-length and the size of the array (or the point up to which it is filled) gets passed along into your function or is a defined constant somwhere, or more commonly a value is picked to indicate the end of the array has been reached (think strings here). Typical values for this are 0 (as you used initially), INT_MIN and INT_MAX (they're defined in limits.h).

The fixed-length bit would be something like:

#define INTARRAY_LENGTH 200

...

int array[INTARRAY_LENGH];

...

for (position = INTARRAY_LENTH-1; position >= 0; position--) {

....

}

And _please_ don't name your array "iar". Hungarian notation is only useful when you write shitty code. If your code is clean, it only obfuscates matters.

Link to comment
Share on other sites

Thanks cooper.

Having talked to a few others, this seems to be the general consensus.

I think PHP and it's min() have softened me up :roll:

I'm just gonna pass the length of the array to the function and use:

int minvalue(int iar[], int size) {



   int ret = iar[0], count=0;



   while (count < size) {



      if (iar[count] < ret) {

         ret = iar[count];

      }

   count++;

   }



return(ret);

}

Oh: one last thing... Why can't I call the array "iar"? I don't know Hungarian. I just meant it to be "Input ARray" :roll:

Link to comment
Share on other sites

Passing size in, too, is just 'the way'. You always have to know where to start (iar being just a memory location) and how far to go, somehow, somewhere. PHP and its ilk merely hide that from you. And you can hide it from yourself, as well, with a class whose contents have as an attribute the length of another attribute, being the contained array. Just easier to keep track of it yourself for small things, hehe.

And call it 'iar' all you want but don't cry when in a month you're looking at your code thinking "Initial Assessment Report? Institute for Aerospace Research? Idioms Are Radical?" ;-)

Link to comment
Share on other sites

It looks ok now. I think what cooper is saying is dont abbreivate that much in your code if you dont need to. It's annoying to others who are trying to figure out what you did, and unessassary(in this instance). but really NBD (no big deal)

I would say just use Array[], I was taught to reserve the use of ivariable for i/o. And using Array[] makes it nice and generic.

Also, dont use something obscure for a name for the variale you are returning. I know you are using ret as an abv. for return but use result instead. Its pretty standard, and is good codeing practice.

people may disagree with some of this but its a matter of personal preferance sometimes, but jsut thought id share what works for me.

[/code]

Link to comment
Share on other sites

Correct me if I'm wrong but wont this work?

int minValue(int data[])

{

    int result = data[0], i = 0;



    while (data[i] != '0')

    {

        if (data[i] < result)

            result = data[i];

    i++;

    }

    return(result); 

}

Link to comment
Share on other sites

Correct me if I'm wrong but wont this work?

int minValue(int data[])

{

    int result = data[0], i = 0;



    while (data[i] != '0')

    {

        if (data[i] < result)

            result = data[i];

    i++;

    }

    return(result); 

}

that would work if you assumed 0, or null, was the last value in the array, otherwise the loop when just stop when it came across a 0. only character arrays are null terminated in C.

Link to comment
Share on other sites

Dayum. I could've sworn I'd answered this. Guess that's what I was doing when the power went over here...

Why can't I call the array "iar"? I don't know Hungarian. I just meant it to be "Input ARray" :roll:

Hungarian notation is the 'art' of prefixing variables with letters that indicate the type of the variable. It's to help make enormous blocks of code more understandable, but any C coder that needs to resort to such tactics should go back to school rather than find clever ways to make it easier to work with the drivel.

To be honest I feel you show poor taste in naming variables.

You use 'iar' for input array. I was unable to guess that, which makes it a shitty name. Obviously it's input, so that bit of the name doesn't add anything. Name the thing 'array' so everybody knows what you're talking about.

Then there's 'count'. What does this variable count exactly? That's right, it doesn't count anything. You use it to specify your current position in the array. So call it position or some such.

Personally I prefer 'result' over 'ret'.

Another thing to consider about your code, what if the size of the array was zero? :twisted:

I think you should do something like this:

int minvalue(int array[], int size) {

    int position = size, result = INT_MAX;

    while (position-- > 0) {

        if (array[position] < result) {

            result = array[position];

        }

    }

    return result;

}

The only assumption this code makes is that the provided array is indeed at least 'size' elements long. When the provided array was empty it returns the highest possible value for an int as an attempt at indication of this situation.

The reason I start at the end of the array and then move backwards is a performance thing. Your CPU has specific instructions for comparing against zero which can yield impressive speed increases.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...