Home > Enterprise >  How to search for maximum element in an array?
How to search for maximum element in an array?

Time:10-08

I have this code and it works fine. However, it can't seem to pass all test case. The program fails if the input size is divisible by 3? how do I fix that? What can I do about my code?


int maxArrayElem(int arr[], int size){
    int tempArr;
    int flag = 0;
    int max;

    for(int i = 0; i<size; i  ){
        if(arr[i]>arr[0]){
            max = arr[i];
        }else if(arr[0]>arr[i]){
            max = arr[0];
        }
        else{
            tempArr = arr[i];
            arr[i] = arr[0];
            arr[0] = tempArr;
        }
    }
    return max;
}
int main(){
    int size;

    printf("Enter size of array: ");
    scanf("%d", &size);
    int arr[size];
    int maxE;
    
        for(int i = 0; i<size; i  ){
        printf("Enter element %d: ", i 1);
        scanf("%d", &arr[i]);
    }
    maxE = maxArrayElem(arr,size);
    printf("Maximum element: %d", maxE);
}```

CodePudding user response:

You can save a lot of work, if this the objective...

#include <stdio.h>
#include <limits.h>

int main() {
    int size;

    printf ("Enter size of array: " );
    scanf( "%d", &size );
    /* omitting test for failure */

    int userVal = INT_MIN, maxE = INT_MIN;
    
    for( int i = 0; i < size; i   ) {
        printf( "Enter element %d: ", i 1 );
        scanf( "%d", &userVal );
        /* omitting test for failure */

        if( maxE < userVal ) maxE = userVal;
    }

    printf( "Maximum value: %d", maxE );

    return 0;
}

CodePudding user response:

the function called maxArrayElem can be optimized into:

int maxArrayElem(int arr[], int size){
    int max = arr[0];

    for(int i = 1; i<size; i  ){
        if(arr[i] > max){
            max = arr[i];
        }
    }
    return max;
}

where a variable called max initially stores the value of arr[0] and see if the next element of the array greater than the current max and if it's the case then make this element the new maximum element and so on...

  •  Tags:  
  • c
  • Related