0

Can anyone help me spot the error in my program in finding the minimum and maximum element in a agiven array. I know that it is a simple error but I cannot figure it out.

#include <stdio.h>
    # define SIZE 10
    int main()
    {
            int min;
            int max;
            int i; //counter variable
            int arr[SIZE] = {2,4,5,7,8,100,4,1};
    
            //check min and max of given array
            min = arr[0];
            max = arr[0];
            for(i =0; i< SIZE;i++)
            {
                    if(arr[i]<min)
                    {
                            min = arr[i];
                    }
                    if(arr[i]>max)
                    {
                            max = arr[i];
                    }
            }
            printf("minimum is %d\n",min);
            printf("maximum is %d\n",max);
    
            return 0;
    }
7
  • Why do you think there is an error? Note, that your array has couple of zeros in it, because the initializer is shorter than SIZE. Commented Mar 1, 2021 at 18:49
  • the minimum value does not get printed correctly. @Eugene Commented Mar 1, 2021 at 18:51
  • Please read the whole comment. I would expect it to print 0 for min Commented Mar 1, 2021 at 18:52
  • 4
    SIZE is 10, the array is initialized with 8 elements only. The rest are zeros Commented Mar 1, 2021 at 18:53
  • 2
    @alex01011 In this case another paragraph applies (because this is not static): If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration. Commented Mar 1, 2021 at 18:58

1 Answer 1

2

You are defining an array of 10 elements and initializing only 8 of them. The remaining two array elements are zero-initialized. That is why your min var is set to 0.

Alternatively define a macro to have a value of 8:

#define SIZE 8

or define an array as following:

int arr[] = {2, 4, 5, 7, 8, 100, 4, 1};

and obtain the array size through the following expression where needed:

sizeof(arr) / sizeof(arr[0])

With arrays of unknown size, the compiler deduces the array size based on the number of initializers, which in our case is 8 and it is the same as if we had written: int arr[8].

Sign up to request clarification or add additional context in comments.

1 Comment

one might want to use sizeof(arr)/sizeof(arr[0]) instead of SIZE if arr is defined this way

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.