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.
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.
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
.
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
.
To understand this better let’s 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<Integer> arr= new ArrayList<>(); for(int i=0;i<n;i++){ arr.add(sc.nextInt()); } if(isListOdd(arr)) { System.out.println("List contains only odd elements"); } else{ System.out.println("list doesn't contains only odd elements"); } } static boolean isListOdd(List<Integer> arr) { for(int i:arr){ if(i%2==0) return false; } return true; } }
Enter the input below
In line 1, we import the java.util
library.
In line 6, we take the input from the user and store it in a variable of int
type size
using the Scanner
class of Java. This integer will be the size of the list.
In line 7, we initialize a list of integers of the ArrayList
type.
In lines 8 to 10, we read integers as the input given by the user and then add them into the list.
In line 12, we call the isListOdd()
function and pass the list of integers as a parameter. This function will return true
if all the numbers in the list are odd; otherwise it will return false
. The output will be printed based on what function returns.
In lines 19 to 26, we define the isListOdd()
function.
Inside the isListOdd()
function, we run a for each
loop . Inside the loop for each element, we are checking whether the number is divisible by two or not. If any one number is divisible by two, then the return value will be false
.
In line 25, after ending the loop, the return value is true
because there aren’t any even numbers in the list.
In this way, we can check if a list of integers contains only odd numbers in Java.
RELATED TAGS
CONTRIBUTOR
View all Courses