Return multiple values from function using pointers

C program to return multiple value from function using pointers

Program

#include<stdio.h>
#include<conio.h>
#define MAX 100

void get_min_max(int *arr, int n, int *min, int *max);

void main()
{
	int arr[MAX], n, i, min, max;

    printf("Enter the size of the array\t:");
    scanf("%d",&n);

    printf("Enter the elements\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }

    get_min_max(arr, n, &min, &max);

    printf("\nMinimum element in array\t:%d",min);
    printf("\nMaximum element in array\t:%d",max);

    getch();
}

void get_min_max(int *arr, int n, int *min, int *max)
{
    int i;

    *min = *(arr+0);
    *max = *(arr+0);

    for(i=0;i<n;i++)
    {
        // Check minimum number
        if(*(arr + i) < *(min))
            *min = *(arr + i);

        // Check maximum number
        if(*(arr + i) > *(max))
            *max = *(arr + i);
    }
}

Output

Enter the size of the array     :7
Enter the elements
12
34
32
45
65
11
43

Minimum element in array        :11
Maximum element in array        :65

Explanation

Function is a set of statements grouped together to perform some specific task. A function can accept any number of parameters (inputs) but can only return (output) single value. However, through the course of programming you will get into situations where you need to return more than one value from a function. Using pointers, one can return multiple values from the function.

In C you can pass parameters to a function either by value or by reference. Changes made to variables passed by reference persists after the function. Hence you can pass any number of parameters as reference, which you want to return from function.

In the above program, two parameters 'min' and 'max' are passed as reference to the function get_min_max. parameters are passed by reference using address of (&) operator.
get_min_max(arr, n, &min, &max);

These parameters when received in function definition, are received in pointer variables. This is because, addresses are passed, and addresses are stored in pointer variables.
void get_min_max(int *arr, int n, int *min, int *max)

In the function, min and max are initialized to first element in the array using the statements
*min = *(arr+0);
*max = *(arr+0);
min and max are compared with rest of the array elements. If any element smaller then min is found, then, min is assigned that small value.
Similarly, if any element greater than 'max' is found then, max is updated with that value.
At the end of the loop, 'min' and 'max' will contain the smallest and largest elements of the array.
The task is accomplished using the code:
for(i=0;i<n;i++)
{
// Check minimum number
if(*(arr + i) < *(min))
*min = *(arr + i);

// Check maximum number
if(*(arr + i) > *(max))
*max = *(arr + i);
}