Search code examples
carraysminimum

find minimum number with 2d array c


i want to find the smallest number in every one row.. but whats wrong in here...

#define NUM_EXAM    3
#define NUM_STUDENT 5

find minimum function :

int find_min(int score[NUM_EXAM][NUM_STUDENT]) {
    int exam;
    int least;
    int k, i, j;

    for (i = 0; i <= NUM_EXAM; i++)
        for (j = 0; j <= NUM_STUDENT; j++)
            least = j;

function :

for (k = j + 1; k < NUM_STUDENT; k++)
            {
                if (score[j] < score[k])
                {
                    k = j;
                }
                exam = score[j];
                score[j] = least;
                score[least] = exam;
            }
    printf("%d", exam);
}

main function :

int main(void) {
    int score[NUM_EXAM][NUM_STUDENT] = { { 60, 80 ,43, 78, 93 } ,{ 75,59,81,77,81 } ,{ 83,74,97,73,81 } };
    find_min(score[NUM_EXAM][NUM_STUDENT]);

    return 0;
}

Solution

  • I noticed some minor things:

    • Already mentioned, you need to change the loop condition to < instead of <=, otherwise you access an element outside of the array size
    • When calling the function, just pass the name of the array, not the size. Check e.g. this
    • As I think you have some overhead in your implementation, I tried to reduce it and if I didn't misunderstand the assignment, the following code shall give you the desired solution:

      #include <stdio.h>
      
      #define NUM_EXAM    3
      #define NUM_STUDENT 5
      
      void find_min(int score[NUM_EXAM][NUM_STUDENT]) {
          int exam;
          int least;
          int i, j;
      
          for (i = 0; i < NUM_EXAM; i++)
          {
              least = 0; 
              for (j = least; j < NUM_STUDENT; j++)
              {
                  if (score[i][j] < score[i][least])
                  {
                      least = j;
                  } 
               }
      
               printf("%d\n", score[i][least]);
          }
      }
      
      int main(void) {
          int score[NUM_EXAM][NUM_STUDENT] = { { 60, 80 ,43, 78, 93 } ,{ 75,59,81,77,81 } ,{ 83,74,97,73,81 } };
          find_min(score);
      
          return 0;
      }