📍📚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>23int findLargest(int *arr, int n) {4 int *max = arr; // Point to first element5 6 for (int i = 1; i < n; i++) {7 if (*(arr + i) > *max) {8 max = arr + i; // Update max pointer9 }10 }11 return *max;12}1314int 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
| Code | Explanation |
|---|---|
| int *max = arr | Initialize max pointer to first element |
| *(arr + i) | Access element at index i using pointer arithmetic |
| max = arr + i | Update max to point to new largest element |
| *max | Dereference 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
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials