Javatpoint Logo

LargestElement

By: raviwo*** On: Fri May 05 14:45:18 IST 2017     Question Reputation0 Answer Reputation0 Quiz Belt Series Points0  0Blank User
1.before for loop;
Create a variable named 'max'.
Assign 'max' the value of first element from array.(We assume this is the max element).

2. Loop:
loop through all element.
3. Inside for loop.
Check if any element is greater than the 'max' then update 'max'. (Basically we maintain the maximum element till i th index in array)
4. outside for loop.
Print final value of 'max'.
Up0Down

 
import java.util.Scanner;
public class Largest_Number
{
public static void main(String[] args)
{
int n, max;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of elements in the array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter elements of array:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
max = a[0];
for(int i = 0; i < n; i++)
{
if(max < a[i])
{
max = a[i];
}
}
System.out.println("Maximum value:"+max);
}
}
Image Created0Down

By: [email protected] On: Thu May 18 15:41:02 IST 2017 Question Reputation0 Answer Reputation0 Belt Series Points0 0User Image
Are You Satisfied :0Yes0No