Open In App

C Program to Find Largest Element in an Array

Improve
Improve
Like Article
Like
Save
Share
Report

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

The brute force approach to find the maximum element in an array is to compare each element with all other elements in the array. But we can optimize it by assuming an element as maximum and start traversing the array. If we find any element greater than the assumed max, we assume that element as the new max.

Algorithm

  1. Create a variable max to store the maximum element so far.
  2. Initialize max with the element on the first index of the array.
  3. Run a loop from the second index to traverse the array.
  4. Compare the variable max with the current element and check,
    1. If the current element is greater than max(max less than current element), update max with the current element.
  5. After the loop, variable max will hold the maximum element in the array.

largest element in the array in C++

C Program to Find the Largest Number in an Array

C




// C program to find maximum in
// arr[] of size n
#include <stdio.h>
 
// C function to find maximum
// in arr[] of size n
int largest(int arr[], int n)
{
    int i;
 
    // Initialize maximum element
    int max = arr[0];
 
    // Traverse array elements from
    // second and compare every
    // element with current max
    for (i = 1; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
 
    return max;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 324, 45, 90, 9808 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Largest in given array is %d", largest(arr, n));
    return 0;
}


Output

Largest in given array is 9808


Complexity Analysis

  • Time complexity: O(N), to traverse the Array completely.
  • Auxiliary Space: O(1), as only an extra variable is created, which will take O(1) space.

Refer to the complete article Program to find largest element in an Array for optimized methods to find the largest element in an array.


Last Updated : 06 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads