-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathtwoSum.java
More file actions
44 lines (33 loc) · 1.22 KB
/
twoSum.java
File metadata and controls
44 lines (33 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package twosum;
import java.util.Scanner;
public class twoSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Get inputs
System.out.println("Enter the size of the array:");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Enter the target sum:");
int target = sc.nextInt();
boolean found = false;
// Find two numbers that add up to target
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
System.out.println("Two numbers found at indices " + i + " and " + j);
System.out.println("Numbers are: " + arr[i] + " + " + arr[j] + " = " + target);
found = true;
break;
}
}
if (found) break;
}
if (!found) {
System.out.println("No two numbers found with the given target sum.");
}
}
}