Skip to main content

Pass 2D array; largest and smallest

Short answer

In the function parameter, declare the array with column size, e.g., int a[][10]. Traverse all elements with nested loops, initializing max and min to a[0][0], update them, and print the largest and smallest.

Explain how 2D array is passed to a function. Write a C program to display largest and smallest elements of a 2D array.

Passing a 2D array to a function

The array name is written in the call: findMinMax(a, r, c);. In the function header the array is declared with all dimensions except the first, for example int a[][10], because the compiler needs the column size to find the address of a[i][j] (address = base + (i × columns + j) × size). The array is passed by address, so no copy is made. The number of rows and columns used are passed as extra arguments.

Program

#include <stdio.h>

void findMinMax(int a[][10], int r, int c)
{
    int max = a[0][0], min = a[0][0];
    for (int i = 0; i < r; i++)
        for (int j = 0; j < c; j++) {
            if (a[i][j] > max) max = a[i][j];
            if (a[i][j] < min) min = a[i][j];
        }
    printf("Largest = %d\nSmallest = %d\n", max, min);
}

int main(void)
{
    int a[10][10], r, c;
    printf("Enter rows and columns: ");
    scanf("%d %d", &r, &c);
    printf("Enter %d elements: ", r * c);
    for (int i = 0; i < r; i++)
        for (int j = 0; j < c; j++)
            scanf("%d", &a[i][j]);
    findMinMax(a, r, c);
    return 0;
}

Sample run

Input: 2 3 4 9 -2 15 7 3

Enter rows and columns: Enter 6 elements: Largest = 15
Smallest = -2

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →