Largest even number

You will be given an array and you are asked to find the largest even number

Input Format
you will be taking a number as an input from STDIN which tells about the length of the array. On another line, array elements should be there with single space between them.

Example :
Input : 
6
78   92   44   63   71   97
Output : 92

Program : 

import java.util.Scanner;
public class LargestEven {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n : ");
                int n = sc.nextInt();
                System.out.print("Enter numbers in array : ");
                int[] arr = new int[n];
                for(int i=0; i<n; i++){
                       arr[i] = sc.nextInt();
                }
        
                int largestEven = 0;
                for(int i=0; i<n; i++){
                if(arr[i]%2 == 0 && arr[i] > largestEven){
                       largestEven = arr[i];
                }
        }

        System.out.print("Largest even number : "+ largestEven);
   }
}

Output :
 
Enter n : 6
Enter numbers in array : 78   92    44 63   71    97
Largest even number : 92

No comments:

Post a Comment