Open In App

C Program to Find Largest Element in an Array using Pointers

Last Updated : 08 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers, the task is to find the largest element in the given array using Dynamic Memory Allocation.

Examples:

Input: arr[] = {4, 5, 6, 7} 
Output: 7
Explanation:
The largest element present in the given array is 7.

Input: arr[] = {8, 9, 10, 12} 
Output: 12
Explanation:
The largest element present in the given array is 12.

Approach

The idea here is to use Dynamic Memory for searching the largest element in the given array. Follow the steps below to solve the problem:

  1. Take N elements and a pointer to store the address of N elements
  2. Allocate memory dynamically for N elements.
  3. Store the elements in the allocated memory.
  4. Traverse the array arr[] to find the largest element among all the numbers by comparing the values using pointers.

Program to Find the Largest Element in an Array using the Pointer

Below is the implementation of the above approach:

C




// C program for the above approach
#include <stdio.h>
#include <stdlib.h>
 
// Function to find the largest element
// using dynamic memory allocation
void findLargest(int* arr, int N)
{
    int i;
 
    // Traverse the array arr[]
    for (i = 1; i < N; i++) {
        // Update the largest element
        if (*arr < *(arr + i)) {
            *arr = *(arr + i);
        }
    }
 
    // Print the largest number
    printf("%d ", *arr);
}
 
// Driver Code
int main()
{
    int i, N = 4;
 
    int* arr;
 
    // Memory allocation to arr
    arr = (int*)calloc(N, sizeof(int));
 
    // Condition for no memory
    // allocation
    if (arr == NULL) {
        printf("No memory allocated");
        exit(0);
    }
 
    // Store the elements
    *(arr + 0) = 14;
    *(arr + 1) = 12;
    *(arr + 2) = 19;
    *(arr + 3) = 20;
 
    // Function Call
    findLargest(arr, N);
    return 0;
}


Output

20 

The complexity of the above method

Time Complexity: O(N)

Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads