Hey there, Today, we’re going to explore a common problem in array : finding the largest element. In this post we will go through the process of finding the largest element in an array using Java.
Introduction :
An array is a data structure that allows you to store multiple values of the same type in a single variable. It’s like a container that holds a collection of elements.
Each element in the array is assigned a unique index, starting from 0, which allows you to access and manipulate individual elements.
Problem :
Here is the simple example of the problem:
Input : arr[ ] = {4,3,2,6,8}
Output : 8
Explanation:
The largest element of the given array is 8.
Solution :
Algorithm :
1 Create and initialize an array.
2. Start by assuming the first element of the array is the smallest and store it in a variable called “max”.
3. Go through each element of the array one by one.
4. Compare each element with the current “max” value.
5. If you find an element smaller than the current “max”, update the value of “max” to that element.
6. Keep repeating steps 3 and 4 until you have checked all the elements in the array.
7. After checking all the elements, the variable “max” will hold the smallest element.
8. Print the value of “max” to display the smallest element.
class SearchMax{ public static void main(String[]args){ int a[]={32,57,63,55,48}; int max=a[0]; for(int i=0;i<a.length;i++){ if(max<a[i]){ max=a[i]; } } System.out.println("The largest element of the given array is "+max); } }
Output :
The largest element of the given array is 63