Find Largest Element in an Array
Understanding Finding Largest Element
Finding the largest element in an array involves scanning the array and keeping track of the maximum value encountered.
We will explore three different methods to find the largest element in an array using C.
Method 1: Using Iteration
This method iterates through the array and finds the largest element.
#include <stdio.h> int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int n = sizeof(arr)/sizeof(arr[0]); int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } printf("Largest element: %d", max); return 0; }
Output: Largest element: 99
Method 2: Using Sorting
This method sorts the array and takes the last element as the largest.
#include <stdio.h> void sort(int arr[], int n) { for (int i = 0; i < n-1; i++) { for (int j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int n = sizeof(arr)/sizeof(arr[0]); sort(arr, n); printf("Largest element: %d", arr[n-1]); return 0; }
Output: Largest element: 99
Method 3: Using Recursion
This method finds the largest element using recursion.
#include <stdio.h> int findMax(int arr[], int n) { if (n == 1) return arr[0]; int max = findMax(arr, n-1); return (arr[n-1] > max) ? arr[n-1] : max; } int main() { int arr[] = {10, 20, 4, 45, 99, 23}; int n = sizeof(arr)/sizeof(arr[0]); printf("Largest element: %d", findMax(arr, n)); return 0; }
Output: Largest element: 99