- 2069 Asar · 2+6 marks
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)(orint *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)
Related questions
- Pass 2D array; largest and smallest · Computer Programming, chapter 7
- Pass student array; display passed students · Computer Programming, chapter 7
- Function returning largest of array · Computer Programming, chapter 7
- Algorithm for largest and smallest · Computer Programming, chapter 2
- Pass array; transpose 3×3 matrix · Computer Programming, chapter 7
- Second largest element using pointer · Computer Programming, chapter 9
- 8086 ALP: largest and smallest, display · Microprocessor, chapter 3
- Two-element array and end fire pattern · Propagation and Antenna, chapter 2