//Find out the values which have sum = 10 from {1,3,5,6,2,4,9}, Ans = 6,4 and 1,9. This is an example only. Let's see the code below for such problems.
package abc;
import java.util.ArrayList;
import java.util.Arrays;
public class FindTargetValuesOfSum {
public static void main(String[] args) {
int[] num = {1,3,5,6,2,4,9,7,8};
int lengthArray = num.length;
ArrayList<Integer> alist = new ArrayList<>();//To display output, but this does not work in this case as shown in the output
int[] array = new int[2];//To display output
for(int i=0;i<lengthArray;i++) {
for(int j=0;j<lengthArray;j++) {
if(num[i]+num[j] ==10) {
System.out.println("Simple output for the sum of 10 can be achieved with : "+num[i]+" , "+num[j]);
array[0]=num[i];
array[1]=num[j];
System.out.println("The output in Array = "+Arrays.toString(array));
alist.add(num[i]);
alist.add(num[j]);
System.out.println("The output in ArrayList = "+alist);//This is not suitable in this case as shown in the result. So, discard the results from this sysout statement. I have kept the result here just to show you what will happen if you use arraylist the way it has been used here.
}
}
}
}
}
Output:
Simple output for the sum of 10 can be achieved with : 1 , 9
The output in Array = [1, 9]
The output in ArrayList = [1, 9]
Simple output for the sum of 10 can be achieved with : 3 , 7
The output in Array = [3, 7]
The output in ArrayList = [1, 9, 3, 7]
Simple output for the sum of 10 can be achieved with : 5 , 5
The output in Array = [5, 5]
The output in ArrayList = [1, 9, 3, 7, 5, 5]
Simple output for the sum of 10 can be achieved with : 6 , 4
The output in Array = [6, 4]
The output in ArrayList = [1, 9, 3, 7, 5, 5, 6, 4]
Simple output for the sum of 10 can be achieved with : 2 , 8
The output in Array = [2, 8]
The output in ArrayList = [1, 9, 3, 7, 5, 5, 6, 4, 2, 8]
Simple output for the sum of 10 can be achieved with : 4 , 6
The output in Array = [4, 6]
The output in ArrayList = [1, 9, 3, 7, 5, 5, 6, 4, 2, 8, 4, 6]
Simple output for the sum of 10 can be achieved with : 9 , 1
The output in Array = [9, 1]
The output in ArrayList = [1, 9, 3, 7, 5, 5, 6, 4, 2, 8, 4, 6, 9, 1]
Simple output for the sum of 10 can be achieved with : 7 , 3
The output in Array = [7, 3]
The output in ArrayList = [1, 9, 3, 7, 5, 5, 6, 4, 2, 8, 4, 6, 9, 1, 7, 3]
Simple output for the sum of 10 can be achieved with : 8 , 2
The output in Array = [8, 2]
The output in ArrayList = [1, 9, 3, 7, 5, 5, 6, 4, 2, 8, 4, 6, 9, 1, 7, 3, 8, 2]
No comments:
Post a Comment