## Interview Question

Software Development Engineer In Test (SDET) InterviewBangalore

Microsoft## Write a program to find out in a sorted array the sum of any two numbers present in the array is closest to the a number given. if you have an array 4, 6, 8,24,36 and the given number is 31 then output should be 24 + 6 = 30

Answer

## Interview Answers

4 Answers

▲

1

▼

main() { int a[]={4, 6, 8,24,36 }; int i=0,j=4; int sum=31,temp,ans; ans=0; while(i

Spandan pathak on

▲

1

▼

int[] arr = new int[] {4, 6, 8, 24, 36}; int number = 60; int diff = 9999; int index = 0; int index2 = 0; for(int i = 0; i < arr.length; i++) { for(int j = i + 1; j < arr.length; j++) { if(Math.abs((arr[i] + arr[j]) - number) < diff) { diff = Math.abs((arr[i] + arr[j]) - number); index = i; index2 = j; } } } int sum = arr[index] + arr[index2]; System.out.println(arr[index] +" + "+ arr[index2] +" = " +sum);

Namrata on

▲

0

▼

static void Main(string[] args) { int[] arr = new int[] { 2, 4, 8, 24, 36, 72, 108 }; int i, j, num = 0, diff = int.MaxValue, a=0, b=0; for ( i = 0; i < arr.Length; i++) { for ( j=0; j < arr.Length; j++ ) { int sum = arr[i] + arr[j]; int newDiff = Math.Abs(sum - num); if (newDiff < diff) { a = arr[i]; b = arr[j]; diff = newDiff; } } } Console.WriteLine("{0} + {1} = {3} is closest to {2}", a, b, num, a+b);

Shital Savekar on

▲

0

▼

Updated Answer which ignores same array elemets to be added for sum. ---------------- static void Main(string[] args) { int[] arr = new int[] { 2, 4, 8, 24, 36, 72, 108 }; int i, j, num = 1111, diff = int.MaxValue, a=0, b=0; for ( i = 0; i < arr.Length; i++) { for ( j=0; j < arr.Length; j++ ) { if (i != j) { int sum = arr[i] + arr[j]; int newDiff = Math.Abs(sum - num); if (newDiff < diff) { a = arr[i]; b = arr[j]; diff = newDiff; } } } } Console.WriteLine("{0} + {1} = {3} is closest to {2}", a, b, num, a+b); } -------------------------- contact.if.urgent@gmail.com

Anonymous on

*One or more comments have been removed.Please see our Community Guidelines or Terms of Service for more information.*

## Add Answers or Comments

To comment on this, Sign In or Sign Up.