Prateek Anand
Prateek Anand

Reputation: 39

How to find the smallest number in the array without sorting it?

I am making a program which finds the smallest number in the array without sorting it.. The output is always 0. Please explain me why?

#include<stdio.h>
#include<conio.h>

void main() {
    int num[5] = {5, 2, 1, 6, 9}, i, j;
    int min = num[0];

    for (i=0; i<5; i++) {
        if (min > num[i+1]) {
            min = num[i+1];
        }
    }
    printf("Smallest number is %d", min);

    getch();
}

Upvotes: 1

Views: 276

Answers (2)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236140

In this expression: num[i+1] you're trying to access an element outside of the array - valid array indexes go from zero to the array's length minus one (which is 4 in this case, but 4+1 is out of the array).

And anyway you should not hard-code array lengths, write your loop like this instead:

for (i = 1; i < num.length; i++) {
    if (num[i] < min) {
        min = num[i];
    }
}

That way it'll always work, it won't matter the actual length of the array.

Upvotes: 1

sve
sve

Reputation: 4356

When i is 4 you are accessing num[5] which is outside the range of the array num. There are no guarantees what num[5] would be but most of the time there are couple trailing 0's after new memory allocation. It should be

for (i=1; i<5; i++) {
    if (min > num[i]) {
        min = num[i];
    }
}

Upvotes: 1

Related Questions