Count Couples in Java
In this program you are given with array along with number, Now you need to find pair in the array that matches with given number. Then finally display the count of pairs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* In this program you are given with array along with number, | |
* Now you need to find pair in the array that matches with | |
* given number. Then finally display the count of pairs. | |
*/ | |
import java.util.*; | |
public class CountCouples { | |
public static void main(String [] args){ | |
Scanner sc=new Scanner(System.in); | |
int size=0; | |
size=Integer.parseInt(sc.nextLine().trim()); | |
String arrayElements=sc.nextLine(); | |
String [] array=arrayElements.split(" "); | |
int num=sc.nextInt(); | |
int count=0; | |
for(int i=0;i<array.length;i++){ | |
for(int j=i+1;j<array.length;j++){ | |
if(num==(Integer.parseInt(array[i])+Integer.parseInt(array[j]))){ | |
count++; | |
} | |
} | |
} | |
System.out.println(count); | |
sc.close(); | |
} | |
} |
Input
4
1 5 -7 1
6
Output:
2 since pairs are {1,5} and {-7,1}
4
1 5 -7 1
6
Output:
2 since pairs are {1,5} and {-7,1}
Comments
Post a Comment