user3533671
user3533671

Reputation: 275

IF statement ignored on last loop

I'm trying to write a piece of code that will take 6 inputs and return smallest and largest number when its done. Problem I'm having is, during 6th loop no matter what number I input, it overwrites my _max variable ignoring condition in IF statement.

#include <stdio.h>
int main()
{
    int     i;
    int     _min;
    int     _max;
    int     input[6];
            _min=20;
            _max=0;

    for(i=1;i<=6;i++)
    {
        scanf("%d",&input[i]);
        if(input[i]<_min)
            {_min=input[i];}
        if(input[i]>_max)
            {_max=input[i];}
        printf("min:%d max:%d\n",_min,_max);
    }
    return 0;
}

Upvotes: 0

Views: 118

Answers (2)

LSerni
LSerni

Reputation: 57378

This is because the elements of the array are numbered from 0 to 5, not 1 to 6.

So since you defined the variables in this order:

int     _min;
int     _max;     <----
int     input[6];

...when you write to input[6], you are actually writing to the memory just after input[5], which is occupied by _max. I guess if you wrote to input[7], you'd see the same thing happening to your _min.

(Note, however, that actual variable allocation is compiler and platform dependant. Where data ends up when it overflows the buffer is not so easy to tell).

Upvotes: 0

Hogan
Hogan

Reputation: 70513

this is what you want... loop over all of them.

for(i=0;i<6;i++)

Upvotes: 2

Related Questions