MIN function

i don't know c has builtin minimum function or not. but i want to write a function which will find minimum number in a integer array.
please hint me i want to use it in a code.
Let's say you have array that contains integers. You define integer called min for example and you put first value of this array into min (min=array[0]). Next thing you have to do is using for loop, to find out if there's any number, that is smaller than value from array[0]. If you find one, you put its value to min variable. In the end, you print min. That's all.
Last edited on
Thanks dear. i have finally do it.
int minimum(int l[], int size) //This function return minimum number in integer array
{
int i,min;
min=0;
for(i=0;i<size;i++) //for loop execute list item time
{

if(l[i]<l[min]) //check array i index element less than array min index element which is zero in first iteration
{
min=l[i]; //if above condition true than array i index element replace array min index element because it is minimum than previous than now it will campare to other remainig items
}
}
return min;
}
if(l[i]<l[min]) min=l[i]
You have a problem; in the first code segment it seems min represents the minimum element number, and in the second it is representing the minimum value. You should just assign i to min instead.
@Zhuge, i think that min=l[i] is correct, but min=0 is not. It should be replaced by min=l[0] and then for loop should start from i=1.

@Masifrz, what if all elements of this array are smaller than zero? That's the reason, why min should be initialized by l[0].
@mtweeman: If you want to do it that way, you'll also want to change the if statement to use min instead of l[min]
@Zhuge, I overlooked this. You're absolutely right.
1
2
3
4
5
6
7
int minimum(int array[], int size) {
    int min = array[0];
    for (int i = 0; i < size; i++) {
        if (array[i] < min) min = array[i];
    }
    return min;
}


That should do it.

Oh, by the way, next time please wrap your code in [code ] [/code ] tags... Without the space in the tags of course. And use proper indentation if possible... Both make it easier to read and cleaner in the post.
Last edited on
Topic archived. No new replies allowed.