Pointer Assignment 16 — Find the Maximum Element in an Array Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Maximum Element in an Array Using Pointers — Traversing the Array with a Pointer

📑 On this page:
  • How Pointer-Based Maximum Finding Works
  • The Three Steps of Finding the Maximum
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to find the maximum element in an array using a function
  • How to traverse an array using a pointer instead of an index
  • How to compare array elements using *ptr
  • Why the first element is initially assumed to be the maximum
  • How pointer arithmetic moves from one array element to the next
  • Why the time complexity of this method is O(n)

How Pointer-Based Maximum Finding Works

Finding the maximum element means identifying the largest value stored in an array. The basic idea is simple: assume the first element is the maximum, then compare every remaining element with it. Whenever a larger value is found, update the maximum.

In the pointer version, instead of using an index such as arr[i], the program uses a pointer ptr to visit each element. The expression *ptr gives the value stored at the current pointer position. After each comparison, ptr++ moves the pointer to the next element.

The function starts with max = *arr, which stores the first element as the initial maximum. Then it begins traversal from arr + 1, because the first element has already been considered. The loop continues while ptr < arr + n, where arr + n is one position past the last element.

💡 In one line: Assume the first element is maximum, traverse the remaining elements with a pointer, and update the maximum whenever *ptr is greater.

Diagram showing a pointer traversing an array to find the maximum element

The Three Steps of Finding the Maximum

Step Pointer operation Effect
1. Set the initial maximumint max = *arr;The first element is assumed to be the largest
2. Traverse and comparefor (ptr = arr + 1; ptr < arr + n; ptr++)Every remaining element is compared with the current maximum
3. Update the maximumif (*ptr > max) max = *ptr;The maximum value is replaced when a larger element is found

This method works for both positive and negative numbers because the first element is used as the initial maximum. It does not depend on the array being sorted, so the elements can be entered in any order.

The pointer version is functionally equivalent to the index version. The main difference is that *ptr replaces arr[i], and ptr++ replaces i++. This helps you practice pointer dereferencing and pointer arithmetic.

Complete C Program

Program: find the maximum element in an array using pointers

#include <stdio.h>

#define MAX 100

/* Find the maximum element using pointers.
   Returns the largest value in the array. */
int find_maximum(const int *arr, int n) {
    const int *ptr;
    int max;

    if (n <= 0) {
        printf("Array is empty.\n");
        return 0;
    }

    max = *arr;                 /* assume first element is maximum */

    for (ptr = arr + 1; ptr < arr + n; ptr++) {
        if (*ptr > max) {
            max = *ptr;         /* update maximum */
        }
    }

    return max;
}

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

    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0 || n > MAX) {
        printf("Invalid size.\n");
        return 1;
    }

    printf("Enter %d integers:\n", n);
    for (i = 0; i < n; i++) {
        if (scanf("%d", &arr[i]) != 1) {
            printf("Invalid input.\n");
            return 1;
        }
    }

    maximum = find_maximum(arr, n);

    printf("\nThe maximum element is: %d\n", maximum);

    return 0;
}
                                    

Program Output

How many elements? 6
Enter 6 integers:
25 89 14 67 93 41

The maximum element is: 93
                                

A second run, with negative numbers:

How many elements? 5
Enter 5 integers:
-10 -45 -3 -78 -20

The maximum element is: -3
                                

In the first run, the pointer compares every element with the current maximum and finally finds 93. In the second run, all values are negative, but the program still correctly identifies -3 as the maximum because it starts with the first element rather than zero.

Step-by-Step Explanation

Let us understand how the pointer visits each element and finds the largest value.

1. The function signature

find_maximum(const int *arr, int n) receives a pointer to the first array element and the number of elements. The const keyword tells the compiler that the function will only read the array and will not modify it.

2. Setting the initial maximum

max = *arr; stores the first array element in max. This is important because the maximum cannot safely be initialized to zero when the array may contain only negative numbers.

3. Starting from the second element

The pointer starts at arr + 1, which is the second element. The first element is already stored in max, so there is no need to compare it with itself.

4. Comparing the current element

The condition *ptr > max compares the value at the current pointer position with the current maximum. If the current element is greater, max is updated to *ptr.

5. Moving the pointer

After each comparison, ptr++ moves the pointer to the next array element. Because ptr is an int pointer, the increment moves forward by sizeof(int) bytes, not by one byte.

6. Loop termination

The loop runs while ptr < arr + n. When ptr reaches arr + n, it has moved past the last valid element, so the traversal stops.

7. Example trace

For the array [25, 89, 14, 67, 93, 41]:

  • Initially, max = 25.
  • The pointer reaches 89. Since 89 > 25, max becomes 89.
  • The pointer reaches 14. Since 14 < 89, max remains 89.
  • The pointer reaches 67. Since 67 < 89, max remains 89.
  • The pointer reaches 93. Since 93 > 89, max becomes 93.
  • The pointer reaches 41. Since 41 < 93, max remains 93.
  • The function returns 93.

8. Pointer version vs index version

The same logic can be written using an index:

int find_maximum_index(const int arr[], int n) {
    int max = arr[0];

    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }

    return max;
}
                                

Both versions produce the same result. The pointer version uses *ptr instead of arr[i] and ptr++ instead of i++. It is useful for learning how arrays and pointers are related in C.

9. Handling negative numbers

Initializing max with the first array element makes the program correct for negative values. If max were initialized to zero, an array such as [-10, -45, -3] would incorrectly return zero as the maximum.

10. Complexity summary

Time complexity is O(n), because every element must be examined once. Best, average, and worst cases are all O(n), since even the largest element may be at the end of the array. Space complexity is O(1), because the function uses only a pointer and one maximum variable.

🎯 Remember this: Start with max = *arr, traverse from arr + 1 to arr + n, compare each value using *ptr > max, and update max whenever a larger element is found.

Frequently Asked Questions

1. Why do we initialize max with the first element?

Initializing max with the first element makes the program correct for all integers, including negative numbers. If max were initialized to zero, an array containing only negative numbers would give an incorrect result.

2. Why does the pointer start at arr + 1?

The first element is already stored in max, so it does not need to be compared again. Starting from arr + 1 avoids one unnecessary comparison.

3. What does *ptr mean?

*ptr dereferences the pointer, meaning it accesses the value stored at the memory location pointed to by ptr. For example, if ptr points to the third array element, *ptr gives the value of that element.

4. Does the array need to be sorted?

No. This method works on both sorted and unsorted arrays because it examines every element individually. Sorting is required for binary search, but not for finding the maximum element.

5. What happens if the array has duplicate maximum values?

The function still returns the same maximum value. For example, in the array [10, 50, 20, 50], it returns 50. If you also need the position of the maximum, you must store the pointer or index whenever a new maximum is found.

6. What is the time complexity of finding the maximum element?

The time complexity is O(n), because the function must check every element at least once. The space complexity is O(1), since only one pointer and one maximum variable are used.

💡 Tip: After implementing this program, modify it to return both the maximum value and its index. You can use pointer subtraction, ptr - arr, to calculate the index of the maximum element.

📖 Related Tutorials

  • 3. Find the Sum of Elements in an Array Using Pointers
  • 4. Reverse an Array Using Pointers
  • 9. Linear Search in an Array Using Pointers
  • 10. Binary Search in a Sorted Array Using Pointers
  • 15. Swap Two Elements in an Array Using Pointers
  • 17. Find the Minimum Element in an Array Using Pointers
  • 18. Sort an Array Using Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 15. Write a program in C language to implement a function to swap two elements in an array using pointers.   ||   Next Topic: -->> 17. Write a program in C to implement a function to find the minimum element in an array using pointers.


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.