Horje
count occurrences in seven integers using java single dimension arrays Code Example
count occurrences in seven integers using java single dimension arrays
public static int count(int[] arr, int num) {
        int count = 0;
        for(int i = 0; i < arr.length; ++i) {   // go through all elements in array
            if(arr[i] == num) { // if num is found, increase count
                count++;    // increment count
            }
        }
        return count;   // return the count of number of occurrences of num in array
    }

    public static boolean checkIfElementAlreadyExists(int[] arr, int index) {
        for(int i = 0; i < index; ++i) {    // go through all elements in array
            if(arr[i] == arr[index]) {  // if item in index already exists in the array
                return true;    // then return true
            }
        }
        return false;   // if element at index does not previously occur, then return false
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] arr = new int[7];
        System.out.print("Enter seven numbers: ");
        for(int i = 0; i < arr.length; ++i) {
            arr[i] = in.nextInt();  // read 7 numbers into array
        }
        for(int i = 0; i < arr.length; ++i) {   // go through all elements
            if(!checkIfElementAlreadyExists(arr, i)) {  // if this element did not already appear before in the array
                System.out.printf("Number %d occurs %d times.\n", arr[i], count(arr, arr[i]));  // then print the number and the number of time it occurs in the array
            }
        }
    }
}




Java

Related
how to add chips dynamically android Code Example how to add chips dynamically android Code Example
how to add element to end of array java Code Example how to add element to end of array java Code Example
activitycompat.requestpermissions not working Code Example activitycompat.requestpermissions not working Code Example
java noclassdeffounderror but class is there Code Example java noclassdeffounderror but class is there Code Example
java convert float to double Code Example java convert float to double Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
10