Java Program to Print Odd Numbers from Array

In this tutorial, we will learn writing Java Program to create an array and print the odd elements stored in the array. Our program will first take the input of array size and then the elements of the array, and then prints all the odd numbers from the elements of the input array.

For example

Case 1: if the user inputs 4 as array size and the array elements as 1,2,3,4.

             The output should be 1, 3.

Case 2: if the user inputs 5 as array size and the array elements as 9,8,7,6,5.

            The output should be 9, 7, 5.

Java Program to Print Odd Numbers from Array

import java.util.*;  
public class Main
{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Java Program to print all Odd numbers in array ");
        System.out.print("Enter the size of array: ");
        int size = sc.nextInt();
        int arr[] = new int[size];
        for(int i=0; i<size; i++) {
            System.out.print("Please give value for index "+ i +" : ");
            arr[i] = sc.nextInt();
        }
        System.out.println("Odd number in array are");
        for(int i=0; i<size; i++)
        {
            if(arr[i]%2!=0){
                System.out.print(arr[i]+"\t");
            }
        }
	}
}

Output

Java Program to print all Odd numbers in array 
Enter the size of array: 5
Please give value for index 0 : 1
Please give value for index 1 : 2
Please give value for index 2 : 3
Please give value for index 3 : 4
Please give value for index 4 : 5
Odd number in array are
1       3       5

Explanations

For the input array [1, 2, 3, 4, 5], while iterating the elements of the array. For elements 1, 3, and 5, the if-condition is satisfied as they are odd numbers and then the numbers 1, 3, and 5 are printed as the output of the program.

What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now