0

from what I've learned, I should be getting the min value of the array, but instead I am getting a large negative number that doesn't exist in my array.

int size;
size = sizeof(array) / sizeof(array[0]);

int min;
min = array[0];

for(int i = 1; i <= size; i++) {
    if(array[i] < min){
        min = array[i];
    }
}

But for some reason I am getting a large negative number: -9.25596e+061

2 Answers 2

6
for(int i = 1; i <= size; i++) {
                //^^^^array index out of bound, since array index starts from 0
   if(array[i] < min){
      min = array[i];
   }
}

You should only compare elements in your array. You tried to access memory not belonging to the array, so you have strange values in that memory.

Your code should look like this:

int min = array[0];
for(int i = 1; i < size; i++) {
   if(array[i] < min){
      min = array[i];
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

To elaborate, C arrays are indexed from 0, not 1, so the first element is at [0], and the last element is at [length-1]
lol Thanks had a dumb moment there...I've been coding for 8 hrs straight.
@tacp can you help me with my avg calculator loop, for some reason I am getting a negative number again like before that should come up
0

When doing your comparison, <= size means you're iterating 1 past the end of the array. It's most likely picking up some really huge garbage value and that becomes the minimum.

Use for (int i = 1; i < size; ++i) { /* ... */ } to get what you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.