arrayscoverflow

Get the maximum element of a two-dimensional array


Task

I want to get the maximum element of a integer two-dimensional array from input.

My code

#include<stdio.h>
int main(void)
{
    /*********Begin*********/
    printf("Input m, n:");
    int m,n;
    int max=0; 
    scanf("%d,%d",&m,&n);
    int s[10][10];
    printf("Input %d*%d array:\n",m,n);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            scanf("%d",&s[i][j]);
        }
    }
    int row,col;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(s[i][j]>max){
                max=s[i][j];
                row=i;
                col=j;
            }

        }
    }
    printf("max=%d, row=%d, col=%d",max,row,col);




    return 0;
}

Tested case

// input
2,1

1

2
// output
Input m, n:Input 2*1 array:
max=2, row=1, col=2

what`s expected:

Input m, n:Input 2*1 array:
max=2, row=2, col=1

Why are the output row and col opposite? Or the output rows and columns are actually incorrect.


Solution

  • All the comments above are valid, and reflected in the code below. I'm giving you the solution not to give you the answer, but to show you some preferred coding practices, as you say you're a student, and coding style is something you would be advised to learn early on. Note in particular my copious use of white space, which makes the code much easier to read.

    (I also pre-defined your matrix so I wouldn't have to enter all the numbers manually; you can undo this.)

    #include <limits.h>
    #include <stdio.h>
    
    int main(void)
    {
    #define NBR_ROWS 5
    #define NBR_COLUMNS 5
    
        const int matrix[NBR_ROWS][NBR_COLUMNS] = {
            { 1, 2, 3, 4, 5},
            { 4, 5, 6, 100, 2 },
            { 3, 2, 1, 5, 6 },
            { 1, 2, 3, 5, 4 },
            { 3, 5, 6, 4, 8 }
        };
        int max = INT_MIN;
        int row;
        int col;
    
        for (int i = 0; i < NBR_ROWS; i++){
            for (int j = 0; j < NBR_COLUMNS; j++) {
                if (matrix[i][j] > max) {
                    max = matrix[i][j];
                    row = i;
                    col = j;
                }
            }
        }
        printf("max=%d, row=%d, col=%d", max, row, col);
    
        return 0;
    }