Skip to main content

Pass array; largest and smallest

Short answer

An array is passed by its name, which is the base address. The function initializes max and min to a[0], loops through all elements, updates both as needed, and prints them.

Explain how array can be passed to functions. Write a program that passes an array to a function and print the largest and smallest element.

Passing an array to a function

In C, an array is passed by giving only its name (without brackets) as the actual argument. The name stands for the address of the first element, so the function receives the address, not a copy of all elements (call by reference).

  • Call: findMinMax(a, n);
  • Definition: void findMinMax(int a[], int n) (or int *a). The size is passed separately because the function cannot know it.
  • Any change made to a[i] inside the function changes the original array.
  • For a 2D array, all dimensions except the first must be written in the parameter, for example int m[][10].

Program

#include <stdio.h>

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

int main(void)
{
    int a[100], n;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter the elements: ");
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    findMinMax(a, n);          /* only the array name is passed */
    return 0;
}

Sample run

Input: 6 34 -5 78 12 0 56

Enter number of elements: Enter the elements: Largest = 78
Smallest = -5

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →