count occurrences in seven integers using java single dimension arrays code example
Example 1: Count Occurrences in Seven Integers Using Java Single Dimension Arrays
import java.util.Scanner;
public class SevenNumbersCount {
public static int count(int[] arr, int num) {
int count = 0;
for(int i = 0; i < arr.length; ++i) {
if(arr[i] == num) {
count++;
}
}
return count;
}
public static boolean checkIfElementAlreadyExists(int[] arr, int index) {
for(int i = 0; i < index; ++i) {
if(arr[i] == arr[index]) {
return true;
}
}
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();
}
for(int i = 0; i < arr.length; ++i) {
if(!checkIfElementAlreadyExists(arr, i)) {
System.out.printf("Number %d occurs %d times.\n", arr[i], count(arr, arr[i]));
}
}
}
}
Example 2: 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) {
if(arr[i] == num) {
count++;
}
}
return count;
}
public static boolean checkIfElementAlreadyExists(int[] arr, int index) {
for(int i = 0; i < index; ++i) {
if(arr[i] == arr[index]) {
return true;
}
}
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();
}
for(int i = 0; i < arr.length; ++i) {
if(!checkIfElementAlreadyExists(arr, i)) {
System.out.printf("Number %d occurs %d times.\n", arr[i], count(arr, arr[i]));
}
}
}
}