Find Number Occurring Odd Number of Times in Java



In this article, we will learn how to find the number in an array that appears an odd number of times using Java. By looping through the array and counting occurrences of each number, the program will detect and return the one with an odd frequency.

Problem Statement

Given an array identify the integer that occurs an odd number of times. Below is the demostration of the same ?

Input

34, 56, 99, 34, 55, 99, 90, 11, 12, 11, 11, 34

Output

The number that occurs odd number of times in the array is
34

Steps to find the number occurring odd number of times

Following are the steps to find the number occurring an odd number of times ?

  • Create a function odd_occurs that takes an integer array and its size as parameters. This function will count occurrences for each element.
  • Loop through the Array by using a for loop to iterate through each element of the array.
  • Count element occurrences for each element, use an inner loop to count how many times it appears in the array.
  • Check for odd occurrence if the count of a number is odd, return that number immediately.
  • If no number with an odd count is found, the function returns -1.
  • In the main method, define an integer array with sample values and call the odd_occurs function to find the odd-occurrence number.
  • Print the result on the console, indicating the number that occurs an odd number of times.

Java program to find the number occurring odd number of times

To find the number occurring an odd number of times, the Java code is as follows ?

public class Demo {
   static int odd_occurs(int my_arr[], int arr_size){
      int i;
      for (i = 0; i < arr_size; i++){
         int count = 0;
         for (int j = 0; j < arr_size; j++){
            if (my_arr[i] == my_arr[j])
               count++;
         }
         if (count % 2 != 0)
         return my_arr[i];
      }
      return -1;
   }
   public static void main(String[] args){
      int my_arr[] = new int[]{ 34, 56, 99, 34, 55, 99, 90, 11, 12, 11, 11, 34 };
      int arr_size = my_arr.length;
      System.out.println("The number that occurs odd number of times in the array is ");
      System.out.println(odd_occurs(my_arr, arr_size));
   }
}

Output

The number that occurs odd number of times in the array is
34

Code explanation

A class named Demo contains a static function named ?odd_occurs'. This function iterates through the integer array and checks to see the number of times these numbers occur. The odd number that occurs frequently is returned as output. In the main function, an integer array is defined, and the length of the array is assigned to a variable. The function is called by passing the array, and its length as parameters. A relevant message is displayed on the console.

Updated on: 2024-11-07T01:07:17+05:30

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements