Define an array of a certain size and enter a few elements in it. These will be the values among which we want to find the largest value. After entering a few elements, the array might appear as follows:
We will use two pointers for finding the largest value in the array. Let's name the two pointers mx and ptr, where the mx pointer will be used to point at the maximum value of the array, and the ptr pointer will be used for comparing the rest of the array elements with the value pointed at by the mx pointer. Initially, both the pointers are set to point at the first element of the array, p[0], as shown in the following diagram:
The ptr pointer is then moved to point at the next element of the array, p[1]. Then, the values pointed at by the mx and ptr pointers are compared. This process continues until all the elements of the array have been compared as follows:
Recall that we want the mx pointer to keep pointing at the larger value. Since 15 is greater than 3 (see Figure 5.13), the position of the mx pointer will be left undisturbed, and the ptr pointer will be moved to point at the next element, p[2], as follows:
Again, the values pointed at by the mx and ptr pointers, which are the values 15 and 70 respectively, will be compared. Now, the value pointed at by the mx pointer is smaller than the value pointed at by the ptr pointer. So, the mx pointer will be set to point at the same array element as ptr as follows:
The comparison of the array elements will continue. The idea is to keep the mx pointer pointing at the largest element in the array, as shown in the following diagram:
As shown in Figure 5.15, 70 is greater than 20, so the mx pointer will remain at p[2], and the ptr pointer will move to the next element, p[4]. Now, the ptr pointer is pointing at the last array element. So, the program will terminate, displaying the last value pointed at by the mx pointer, which also happens to be the largest value in the array.
Let's use GCC to compile the largestinarray.c program as the following statement:
D:\CBook>gcc largestinarray.c -o largestinarray
If you get no errors or warnings, that means that the largestinarray.c program has been compiled into an executable file, largestinarray.exe. Let's now run this executable file as follows:
D:\CBook>./largestinarray
How many elements are there? 5
Enter 5 elements
15
3
70
35
20
Largest value is 70
You can see that the program displays the maximum value in the array
Voilà! We've successfully found the largest value in an array using pointers. Now, let's move on to the next recipe!