- Define a macro by the name max with a size of 100 as follows:
#define max 100
- Define a p integer array of a max size, as demonstrated in the following code:
int p[max]
- Specify the number of elements in the array as follows:
printf("How many elements are there? ");
scanf("%d", &n);
- Enter the elements for the array as follows:
for(i=0;i<n;i++)
scanf("%d",&p[i]);
- Define two mx and ptr pointers to point at the first element of the array as follows:
mx=p;
ptr=p;
- The mx pointer will always point at the maximum value of the array, whereas the ptr pointer will be used for comparing the remainder of the values of the array. If the value pointed to by the mx pointer is smaller than the value pointed at by the ptr pointer, the mx pointer is set to point at the value pointed at by ptr. The ptr pointer will then move to point at the next array element as follows:
if (*mx < *ptr)
mx=ptr;
- If the value pointed at by the mx pointer is larger than the value pointed to by the ptr pointer, the mx pointer is undisturbed and is left to keep pointing at the same value and the ptr pointer is moved further to point at the next array element for the following comparison:
ptr++;
- This procedure is repeated until all the elements of the array (pointed to by the ptr pointer) are compared with the element pointed to by the mx pointer. Finally, the mx pointer will be left pointing at the maximum value in the array. To display the maximum value of the array, simply display the array element pointed to by the mx pointer as follows:
printf("Largest value is %d\n", *mx);
The largestinarray.c program for finding out the largest value in an array using pointers is as follows:
#include <stdio.h>
#define max 100
void main()
{
int p[max], i, n, *ptr, *mx;
printf("How many elements are there? ");
scanf("%d", &n);
printf("Enter %d elements \n", n);
for(i=0;i<n;i++)
scanf("%d",&p[i]);
mx=p;
ptr=p;
for(i=1;i<n;i++)
{
if (*mx < *ptr)
mx=ptr;
ptr++;
}
printf("Largest value is %d\n", *mx);
}
Now, let's go behind the scenes.