Q17.Write a code to find largest element in an array.
Solution :- In this program, we will find the largest/Maximum value element in an array.
For Example :-
input : arr[]={ 2, 5, 3, 6, 4 }
output : 6
So as we can see that the largest element in arr[] = { 2, 5, 3, 6, 4 } is 6 so the output is 6.
Algorithm for Array Largest Number
START
Step 1 → Take an array Arr and define its values
Step 2 → Declare one variable (VAR) and assign 1st element of array to it
Step 3 → Loop for each value of Arr Repeat Step 4
Step 4 → If Arr[I] > VAR, Assign Arr[I] to VAR
Step 5 → After loop finishes, Display VAR which holds the largest element of array
STOP
Code for Array Largest Number
#include <stdio.h>
int main() {
int i, arr[5]={ 2, 5, 3, 6, 4};
int VAR = arr[0];
for (i = 1; i < 5; ++i) {
if (VAR < arr[i])
VAR = arr[i];
}
printf(“Largest element in an Array is = %d”, VAR);
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int i, arr[5]={ 2, 5, 3, 6, 4};
int VAR = arr[0];
for(i = 1;i < 5; ++i)
{
if(VAR < arr[i])
VAR = arr[i];
}
cout << “Largest element in an Array is = ” << VAR;
return 0;
}
public class LFC {
public static void main(String[] args) {
int[] numArray = { 2, 5, 3, 6, 4};
int largest = numArray[0];
for (int num: numArray) {
if(largest < num)
largest = num;
}
System.out.format(“Largest element in an Array is = %d”, largest);
}
}
number = [2, 5, 3, 6, 4]
largest_number = max(number);
print(“Largest element in an Array is = “, largest_number)
// Returns maximum in array
function getMax($arr)
{
$n = count($arr);
$max = $arr[0];
for ($i = 1; $i < $n; $i++)
if ($max < $arr[$i])
$max = $arr[$i];
return $max;
}
// Driver code
$arr = array(2, 5, 3, 6, 4);
echo “Largest element in an Array : “;
echo(getMax($arr));
Output
Largest element in an Array is =6
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number