Google News
logo
C Program to Find Largest Element in an Array
In this example, you will learn to display the largest element entered by the user in an array.

Example : Largest Element in an array :

Program :
#include <stdio.h>
int main() {
  int n;
  double arr[100];
  printf("Enter the number of elements (1 to 100): ");
  scanf("%d", &n);

  for (int i = 0; i < n; ++i) {
    printf("Enter number%d: ", i + 1);
    scanf("%lf", &arr[i]);
  }

  // storing the largest number to arr[0]
  for (int i = 1; i < n; ++i) {
    if (arr[0] < arr[i]) {
      arr[0] = arr[i];
    }
  }

  printf("Largest element = %.2lf", arr[0]);

  return 0;
}
Output :
Enter the number of elements (1 to 100): 5
Enter number1: 21.5
Enter number2: 53.4
Enter number3: 80.7
Enter number4: 16
Enter number5: 1.8
Largest element = 80.70
In the following another program we are initializing a variable (max_element) with the first element of given array and then we are comparing that variable with all the other elements of the array using loop, whenever we are getting an element with the value greater than max_element, we are moving that element to max_element and moving further with the same approach to get the largest element in the max_element variable.

Example 2 : Largest Element in an array :

Program :
#include <stdio.h>
 
/*  This is our function to find the largest
 * element in the array arr[]
 */
int largest_element(int arr[], int num)
{
    int i, max_element;
    
    // Initialization to the first array element
    max_element = arr[0];
 
    /* Here we are comparing max_element with
     * all other elements of array to store the 
     * largest element in the max_element variable
     */
    for (i = 1; i < num; i++)         
        if (arr[i] > max_element)
            max_element = arr[i];
 
    return max_element;
}
 
int main()
{
    int arr[] = {1, 26, 48, 136, 19, -153, 124};
    int n = sizeof(arr)/sizeof(arr[0]);
    printf("Largest element of array is %d", largest_element(arr, n));
    return 0;
}
Output :
Largest element of array is 136