Skip to content

Commit 91e93df

Browse files
committed
Two-Sum in Java
1 parent 10a0de1 commit 91e93df

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Java/twoSum.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package twosum;
2+
3+
import java.util.Scanner;
4+
5+
public class twoSum {
6+
7+
public static void main(String[] args) {
8+
9+
Scanner sc = new Scanner(System.in);
10+
11+
// Get inputs
12+
System.out.println("Enter the size of the array:");
13+
int n = sc.nextInt();
14+
15+
int[] arr = new int[n];
16+
System.out.println("Enter " + n + " integers:");
17+
for (int i = 0; i < n; i++) {
18+
arr[i] = sc.nextInt();
19+
}
20+
21+
System.out.println("Enter the target sum:");
22+
int target = sc.nextInt();
23+
24+
boolean found = false;
25+
26+
// Find two numbers that add up to target
27+
for (int i = 0; i < n; i++) {
28+
for (int j = i + 1; j < n; j++) {
29+
if (arr[i] + arr[j] == target) {
30+
System.out.println("Two numbers found at indices " + i + " and " + j);
31+
System.out.println("Numbers are: " + arr[i] + " + " + arr[j] + " = " + target);
32+
found = true;
33+
break;
34+
}
35+
}
36+
if (found) break;
37+
}
38+
39+
if (!found) {
40+
System.out.println("No two numbers found with the given target sum.");
41+
}
42+
}
43+
}
44+

0 commit comments

Comments
 (0)