Search code examples
calgorithminitializationmaxmin

Unexpected return value in this C program


I wrote a C program to find the difference in indices of the largest even number and the smallest even number in an array(here 0 is considered as an even number and from the testcases it definitely didn't look like the array should be sorted). It will return a value or No if the array has one element or no even numbers in that array.

#include <math.h>
#include <stdio.h>



int main() {
  
    int n,small,big,a[50],b1,s1,diff;
    scanf("%d",&n);
    for(int i =0;i<n;i++){
        scanf("%d",&a[i]);
    }
    


    
    small = a[0];
    big = a[0];
    
    for (int i = 1; i < n; i++)
    {
        if (a[i] < small && a[i]%2 == 0)
        {
            small = a[i];
            s1 = i;
        }
        if (a[i] > big && a[i]%2 == 0)
        {
            big = a[i];
            b1 = i;
        }
    }
    diff = b1-s1;
    
    if(diff==0){
      printf("NO");
    }
    else{
      printf("%d",diff);
    }
    
    return 0;
}

When I give as input

4
120 0 4 7

It doesn't return 1 . It returns 32657. What logic am I not understanding here? Please help me.


Solution

  • In this code snippet

    small = a[0];
    big = a[0];
    

    you also need to initialize s1 and b1

    s1 = 0;
    b1 = 0;
    

    In general your approach is incorrect because a[0] can be an odd number and can be the greatest or smallest number in the array.

    So at first you need to find in the array the first even number and if such a number exists (for example at index i) then write

    small = a[i];
    big = a[i];
    s1 = i;
    b1 = i;
    

    Pay attention to that you can include the header <stdio.h> in fact in any place in your program because after the first inclusion of the header all other headers will not be actually included. But do not do that because it makes your program very strange.:)

    So remove this directive in main

    #include <stdio.h>
    

    Also the directive

    #include <math.h>
    

    is redundant because neither declaration from the header is used in your program. You may also remove it.