📍📚Intermediate

Find Largest Element Using Pointers

Array max with pointers

Finding the largest element using pointers demonstrates how pointers can traverse arrays efficiently. Instead of using array indices, we use pointer arithmetic.

C Program to Find Largest Element Using Pointers

largest_using_pointers.c
C
1#include <stdio.h>
2
3int findLargest(int *arr, int n) {
4 int *max = arr; // Point to first element
5
6 for (int i = 1; i < n; i++) {
7 if (*(arr + i) > *max) {
8 max = arr + i; // Update max pointer
9 }
10 }
11 return *max;
12}
13
14int main() {
15 int arr[] = {45, 89, 23, 67, 12, 90, 34};
16 int n = sizeof(arr) / sizeof(arr[0]);
17
18 printf("Array: ");
19 for (int *p = arr; p < arr + n; p++) {
20 printf("%d ", *p);
21 }
22
23 printf("\nLargest element: %d\n", findLargest(arr, n));
24
25 return 0;
26}
Output

Array: 45 89 23 67 12 90 34

Largest element: 90

📖 Code Explanation

CodeExplanation
int *max = arrInitialize max pointer to first element
*(arr + i)Access element at index i using pointer arithmetic
max = arr + iUpdate max to point to new largest element
*maxDereference to get the value

🎯 Key Takeaways

*(arr + i) ≡ arr[i]
Pointers can store address of max
Array name decays to pointer
p++ moves to next element