The Program in C to print the largest element of an array using a function is given below:
#include <stdio.h>
int find_largest(int arr[], int size) {
// Function to find the largest element in an array
int largest = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int arr[size];
printf("Enter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
int largest = find_largest(arr, size);
printf("The largest element in the array is: %d", largest);
return 0;
}
Output:
Enter the size of the array: 3
Enter the elements of the array: 12
45
23
The largest element in the array is: 45
Pro-Tips💡
This program defines a function find_largest()
that takes in two parameters: the array and its size.
Inside the function, it initializes a variable largest
to the value of the first element of the array, and then iterates through the array, comparing each element with the current value of largest
.
If an element is found that is greater than the current value of largest
, the value of largest
is updated to the value of that element.
The function then returns the value of largest
. In the main()
function, the program prompts the user to enter the size of the array and the elements of the array one by one.
Then the find_largest()
function is called with the array and its size as arguments, and the returned value is stored in the largest
variable.
The largest element of the array is then printed to the console.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.