mmayoub

School, 07.09.2017, Ex4, find two numbers with given sum

Sep 7th, 2017
168
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. public class Ex4 {
  3.     // Write a Java program to find the sum of the two elements of a given array
  4.     // which is equal to a given integer.
  5.     // Sample array: [8,1,2,4,5,6]
  6.     // Target value: 6.
  7.  
  8.     public static void main(String[] args) {
  9.         int[] arr = { 8, 1, 2, 4, 5, 6 };
  10.         int sum = 6;
  11.         boolean found = false;
  12.  
  13.         for (int i = 0; i < arr.length - 1; i += 1) {
  14.             for (int j = i + 1; j < arr.length; j += 1) {
  15.                 if (arr[i] + arr[j] == sum) {
  16.                     System.out.println(arr[i] + "+" + arr[j] + " = " + sum);
  17.                     found = true;
  18.                     // return;
  19.                 }
  20.             }
  21.         }
  22.  
  23.         if (found == false)
  24.             System.out.println("There is no two numbers with sum of " + sum);
  25.  
  26.     }
  27.  
  28. }
RAW Paste Data