Open In App

C Program to Find Largest Element in an Array

Last Updated : 20 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to find the largest element in the array using a C program.

The simplest method to find the largest element in the array is by iterating the array and comparing each element with the assumed maximum and updating it when the element is greater.

C
#include <stdio.h>

int findMax(int arr[], int n) {
  
  	// Assume the first element is the largest
    int max = arr[0];
    for (int i = 1; i < n; i++) {
      
      	// Update max if arr[i] is greater
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

int main() {
    int arr[] = {5, 2, 7, 6};
    int n = sizeof(arr) / sizeof(arr[0]);
  
    printf("%d\n", findMax(arr, n));
    return 0;
}

Output
7

Explanation: This method is simply the linear search algorithm modified to find the minimum element.

There are also a few more methods to find the largest element in the array that are useful in different cases. Let’s take a look at them one by one:

Using Recursion

The recursive approach works similar to the above method. It compares the element one by one using recursion and updates the assumed maximum if the larger value is found.

C
#include <stdio.h>

// Recursive approach to find the maximum element
int findMax(int arr[], int n) {
  
    // Base case: Only one element
    if (n == 1) return arr[0];
  
  	// Find  maximum from the rest of the array
    int max = findMax(arr, n - 1);
  
  	// Return smaller element between curent element
  	// or maximum element in rest of the array
    return arr[n - 1] > max ? arr[n - 1] : max;
}

int main() {
    int arr[] = {5, 2, 7, 6};
    int n = sizeof(arr) / sizeof(arr[0]);
  
	// Finding and printing the maximum element
    printf("%d\n", findMax(arr, n));
  
    return 0;
}

Output
7

Using Sorting

in an array sorted in ascending order, the maximum element is present at the end i.e. (n – 1)th index. The array can be sorted using qsort() function with a custom comparator for ascending order.

C
#include <stdio.h>
#include <stdlib.h>

// Comparator function for qsort (ascending order)
int compare(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);  
}

int findmax(int arr[], int n) {
  
  	// Sort the array using qsort
    qsort(arr, n, sizeof(int), compare);
  	
  	// The last element is largest after sorting
  	return arr[n - 1];
}

int main() {
    int arr[] = {5, 2, 7, 6};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Find and print the maximum element in arr
    printf("%d\n", findmax(arr, n));
  
    return 0;
}

Output
7

This method is less efficient than linear search for just finding the maximum element but more suitable for finding the n-th largest element.



Next Article

Similar Reads