There are multiple way to find the missing and no duplicate number in an array 1 to 10.
Using Boolean validate() method :-
- First we take one input array from 1 to 10.
- Now iterate this array number from for loop.
- Create one boolean validate method, pass array data and total data from index i
- Inside validate method its compare(arr[j] == k) array data with index.
- if equals its return true else false.
- Now depend on the status its print missing number.
Using a Mathematical Method :-
- First we take one input array from 1 to 10.
- Sum the first n natural numbers by using the formula sum=n*(n+1)/2.
- To keep the total of the array’s items, create the variable actualSumValue.
- Now iterate this array number from for loop.
- Here actualSumValue should be updated to actualSumValue= actualSumValue.+ b[i].
- Print (sum – actualSumValue) to give missing number.
public class FindMissingNumber {
public static void main(String[] args) {
// Using Boolean validate() method
int a[] = { 1, 2, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 1; i < a.length; i++) {
boolean isStatus = validate(a, i);
if (isStatus == false) {
System.out.println("from Boolean validate() method to find the missing number:- " + i);
break;
}
}
// Using a Mathematical Method
int b[] = { 1, 2, 4, 5, 6, 7, 8, 9, 10 };
int sum = (10) * (10 + 1) / 2; // formula sum=n*(n+1)/2
int actualSumValue = 0;
for (int i = 0; i < b.length; i++) {
actualSumValue = actualSumValue + b[i];
}
System.out.println(
"from Mathematical Method to find the missing number in second way:- " + (sum - actualSumValue));
}
public static boolean validate(int arr[], int k) {
for (int j = 0; j < arr.length; j++) {
if (arr[j] == k) {
return true;
}
}
return false;
}
}
Output :-
from Boolean validate() method to find the missing number:- 3
from Mathematical Method to find the missing number in second way:- 3