Given a list of integers return true if any of the numbers are even

How to check if a list contains only odd numbers in Java

In this shot, we will discuss how to check if a list of integers contains only odd numbers in Java.

If a number is not completely divisible by two, then it is considered an odd number. For such numbers, dividing them by two always leaves a remainder of one.

If the digit of the unit place of any number belongs to 1, 3, 5, 7, or 9 then the number is odd.

Example

11 is an odd number because dividing by two leaves 1 as a remainder. It is not completely divisible by 2. The 1 in the unit place indicates the number as odd.

Solution approach

We are going to create an isListOdd[] function that takes a list of integers as input and returns true if all the elements in the list are odd. Otherwise, it returns false.

How to check if a list of integers contains only odd numbers

For this, you need to traverse through the list once and check whether each integer is completely divided by two or not. We can use a for loop or a for each loop for this. In this way, if it finds a number that is divisible by two in the list, it will simply return false.

Code

To understand this better lets look at the code snippet.

To run the code, enter the size of the list first, followed by the elements of the list. Put a space between each integer.

Sample input: 4 3 5 7 9

Here the size of the list is four and the elements are 3, 5, 7, and 9.

import java.util.*; class OddElement { public static void main[String[] args] { Scanner sc= new Scanner[System.in]; System.out.println["Enter the size of list"]; int n= sc.nextInt[]; List arr= new ArrayList[]; for[int i=0;i

Chủ Đề