C Online Compiler
Example: Find Largest Element in Array (Using Function) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Largest Element in Array (Using Function) #include <stdio.h> // Function to find the largest element in an array int findLargest(int arr[], int size) { // Step 1: Handle edge case for an empty array if (size <= 0) { printf("Error: Array is empty or has invalid size.\n"); return -1; // Or throw an error, depending on desired error handling } // Step 2: Initialize 'max' with the first element int max = arr[0]; // Step 3: Iterate through the rest of the array for (int i = 1; i < size; i++) { // Step 4: Update 'max' if a larger element is found if (arr[i] > max) { max = arr[i]; } } // Step 5: Return the largest element return max; } int main() { // Step 1: Declare and initialize an array int myNumbers[] = {55, 10, 99, 3, 72, 8}; int arraySize = sizeof(myNumbers) / sizeof(myNumbers[0]); // Step 2: Call the function to find the largest element int largest = findLargest(myNumbers, arraySize); // Step 3: Print the result if the function returned a valid value if (largest != -1) { // Check for the error return value printf("The largest element in the array is: %d\n", largest); } // Example with an empty array to show error handling int emptyArray[] = {}; int emptySize = 0; findLargest(emptyArray, emptySize); // This will print the error message return 0; }
Output
Clear
ADVERTISEMENTS