Pages

Find the missing number in sorted array ?

 Find the missing number in sorted array ?

>> In Java, we can find missing number using for loop.

logic: (sum of numbers in given array range)-(sum of numbers in given array)

public class findMissingNumber {
public static void main(String[] args) {
int numbers[] = { 1, 2, 3, 4, 6 };
int sum = 0;
// add numbers in given array
for (int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
System.out.println("sum of numbers in given array=" + sum);

int sum1 = 0;
// add numbers till max range in given array
for (int j = 1; j <= 6; j++) {
sum1 = sum1 + j;
}
System.out.println("sum of numbers=" + sum1);

System.out.println("Missing number=" + (sum1 - sum));
}
}
Output:
Java find missing number
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.