Home > Net >  Im trying to find the max and min value and its respective index. However I cant get the indexmin
Im trying to find the max and min value and its respective index. However I cant get the indexmin

Time:10-03

Find the minimum element of the array and its corresponding index. I can't get the the minimum index to work. Do I add else statement under each if statement?

#include<stdio.h>

int main()
{
int array[10]={1,2,3,4,5,6,7,8,9,10} , i;
    **//finding max and min, and its respective index**
    int max = array[0] , min = array[0];
    int indmin , indmax;

    for( i = 0 ; i < 10 ; i   )
    {
        if(array[i] > max) 
        {
            max = array[i];
            indmax = i;

        }
        if(array[i] < min)
        {
            min = array[i];
            indmin = i;
        }


        }

//print the max and min value and its indexs
    printf("\nMaximum element is %d\t index is %d", max , indmax);
    printf("\nMinimum element is %d\t index is %d", min , indmin);

}

CodePudding user response:

Initialize indmin and indmax. When defining the array leave out the size so it's derived from the data. When iterating over the array use sizeof(array) / sizeof(*array) to let compiler determine the size of the array instead of hard-coding it. Minimize scope of variable i. Use a function to print output for less duplication:

#include <stdio.h>

void print(const char *prompt, int value, int index) {
    printf("%s element is %d\t index is %d\n", prompt, value, index);
}

int main() {
    int array[]={1,2,3,4,5,6,7,8,9,10};

    int min = array[0];
    int indmin = 0;
    int max = array[0];
    int indmax = 0;
    for(int i = 0; i < sizeof(array) / sizeof(*array); i  ) {
        if(array[i] > max) {
            max = array[i];
            indmax = i;
        }
        if(array[i] < min) {
            min = array[i];
            indmin = i;
        }
    }
    print("Maximum", max, indmax);
    print("Minimum", min, indmin);
}

You could refactor this by creating a struct to keep the value and index together:

#include <stdio.h>

struct value_index {
    int value;
    int index;
};

void print(const char *prompt, struct value_index *vi) {
    printf("%s element is %d\t index is %d\n", prompt, vi->value, vi->index);
}

int main() {
    int array[]={1,2,3,4,5,6,7,8,9,10};

    struct value_index min = { array[0], 0 };
    struct value_index max = { array[0], 0 };
    for(int i = 0; i < sizeof(array) / sizeof(*array); i  ) {
        if(array[i] > max.value) {
            max.value = array[i];
            max.index = i;
        }
        if(array[i] < min.value) {
            min.value = array[i];
            min.index = i;
        }
    }
    print("Maximum", &max);
    print("Minimum", &min);
}

Or you could realize that you only need the original array along with the two indices. To make my version even better than @Fe2O3's answer, I used a macro to make mine smaller (and if bait works then I will claim mine is easier to read) :-)

#include <stdio.h>

void print(const char *prompt, int *arr, int index) {
    printf("%s element is %d\t index is %d\n", prompt, arr[index], index);
}

int main() {
    int array[]={1,2,3,4,5,6,7,8,9,10};

    int indmin = 0;
    int indmax = 0;
    for(int i = 0; i < sizeof(array) / sizeof(*array); i  ) {
#define CMP_AND_SET(OP, V) if(array[i] OP array[V]) V = i
        CMP_AND_SET(<, indmin);
        CMP_AND_SET(>, indmax);
#unset CMP_AND_SET
    }
    print("Maximum", array, indmax);
    print("Minimum", array, indmin);
}

CodePudding user response:

Leaving variables uninitialised is asking Demon of Hard-To-Find-Bugs to co-author your code. Define variables close to where they are used to increase clarity. And, don't define more variables than you need. (Common beginner mistake to make another copy "just in case"...)

// use the spacebar to increase readability
#include <stdio.h>

int main() {
    // let the compiler assign the size of an initialised array
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    // use fewer variables
    int indmin = 0, indmax = 0;

    // don't compare an element to itself
    for( int i = 1 ; i < sizeof array/sizeof array[0]; i   )
        if( array[ i ] > array[ indmax ] )
            indmax = i; // updated

        else
        if( array[ i ] < array[ indmin ] )
            indmin = i; // updated
        // don't add unnecessary parentheses (imho)

    // use '\n' at the END of output. sometimes needed to 'flush' output buffer
    printf("Maximum element is %d\t index is %d\n", array[ indmax ] , indmax);
    printf("Minimum element is %d\t index is %d\n", array[ indmin ] , indmin);

    return 0;
}
Maximum element is 10    index is 9
Minimum element is 1     index is 0

EDIT:
So, there's a friendly competition going on in this question... :-)

How's this:

#include <stdio.h>

int main() {
    // let the compiler assign the size of an initialised array
    // use shorter names to expose operations
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int iMin = 0, iMax = 0;

    // don't compare an element to itself
    for( int i = 1; i < sizeof arr/sizeof arr[0]; i   ) {
        // use "branchless" coding for speed.
        int n = arr[i] > arr[iMax];
        iMax = n*i   !n*iMax;
        n = arr[i] < arr[iMin];
        iMin = n*i   !n*iMin;
    }

    // use '\n' at the END of output. sometimes needed to 'flush' output buffer
    // reduce duplication of static data
    char *fmt = "%s element is %d\t index is %d\n";
    printf( fmt, "Maximum", arr[ iMax ], iMax );
    printf( fmt, "Minimum", arr[ iMin ], iMin );

    return 0;
}

Same thing without comments:

#include <stdio.h>

int main() {
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int iMin = 0, iMax = 0;

    for( int i = 1; i < sizeof arr/sizeof arr[0]; i   ) {
        int n = arr[i] > arr[iMax];
        iMax = n*i   !n*iMax;
        n = arr[i] < arr[iMin];
        iMin = n*i   !n*iMin;
    }

    char *fmt = "%s element is %d\t index is %d\n";
    printf( fmt, "Maximum", arr[ iMax ], iMax );
    printf( fmt, "Minimum", arr[ iMin ], iMin );
    return 0;
}

Same output.
Ball's in your court @Allan :-)

  • Related