Question: What is pair Sum ?
Ans:
"Pair sum" ka matlab hota hai ki aapko ek array mein diye gaye kisi bhi do numbers ka sum nikalna hai. Java mein pair sum nikalne ke liye aap ek array mein se do numbers ko select karke unka sum calculate kar sakte hain. Yeh kaam aksar loops (for loop ya while loop) ka istemal karke kiya jata hai.
Ek example ke roop mein, agar aapke paas ek array hai [2, 4, 6, 8, 10] aur aapko 10 ke liye pair sum nikalna hai, to aap is tarah se kar sakte hain:
package aRray;
import java.util.*;
public class pairSum {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int count =0;
int targetSum = 10; // yaha jo add krke chahiye wo dalenge
int [] arr = new int[size]; // array of size
for(int i = 0; i < size; i++) {
arr[i] = scan.nextInt();}
for(int i = 0 ; i < size; i++) {
for(int j = i+1; j < size; j++) {
if(arr[i]+arr[j] == targetSum) {
count++;
}
}
}System.out.print(count);
}
}
Loop ke bahar aake ham count ko print kr rhe
Comments
Post a Comment