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.



/**
* 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();
}
}
view raw CountCouples hosted with ❤ by GitHub
Input
4
1 5 -7 1
6

Output:
2  since pairs are {1,5} and {-7,1}

Comments

Popular posts from this blog

Reasoning-Number Series

Profit and Loss

Reasoning-Letter Series