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 JavaIn this shot, we will discuss how to check if a list of integers contains only odd numbers in Java. Show 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.
Example11 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 approachWe 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 numbersFor 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. CodeTo 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.
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 Enter the input below Run Explanation
In this way, we can check if a list of integers contains only odd numbers in Java. |