SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Java Primer
Exercise:
Exercises
Question:17 | ISBN:9781118771334 | Edition: 6

Question

Write a short Java method that takes an array of int values and determines if there is a pair of distinct elements of the array whose product is even.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer


// java program to check if there is a pair of distinct elements of the array whose product is even.

package java_problems_datastructures;


public class CheckForEvenProduct {

	// initilizing the array
	static int[] arrayOfIntegers = {32, 54, 3, 8, 787, 45, 1, 4, 9, 7 };

	
	public boolean doesItContainsEvenProduct(int[] arr) {
		// set boolean value to false first
		boolean isEvenProduct = false;
		
		for (int i = 0; i < arr.length; i++) {
			for (int j = 1; j < arr.length; j++) {
				// logic is both should be distinct and there shouldn't be any reminder
				// we implemented that logic below
				if (arr[j] != arr[i] && ((arr[j] * arr[i]) % 2 == 0))
					isEvenProduct = true;
			}
		}
		return isEvenProduct;
	}

	public static void main(String[] args) {

		CheckForEvenProduct check = new CheckForEvenProduct();
		System.out.println("Does the array contains product of two distict elemets which is even? " + check.doesItContainsEvenProduct(arrayOfIntegers));
		
	}

}

Output:

case1: 

32 54 3 8 787 45 1 4 9 7 
Does the above array contains product of two distict elemets which is even? true

case 2:

9 7 1 3 
Does the above array contains product of two distict elemets which is even? false

 

 

 

0 0

Discussions

Post the discussion to improve the above solution.