2 test cases are not working in my code

please take a look at my code and suggest some necessary changes so that all the test cases will work properly

Hi@akshay9009
please share your code here.

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int arr[]=new int[n];
for(int i=0;i<arr.length;i++){
arr[i]=scan.nextInt();
}
int sum=scan.nextInt();
sum(arr,sum);
}
public static void sum(int arr[],int sum){
int num1=0;
int num2=0;

	for(int counter=0;counter<arr.length;counter++){
		
		for(int j=counter;j<arr.length;j++){
		
			if(arr[counter]+arr[j]==sum){
				num1=arr[counter];
				num2=arr[j];
				System.out.println(num1 +" and "+num2);
			}
		}
		
		
	}
	System.out.println("");

}

}

see first of all you are starting your second loop with j=counter this means you are repeating that number twice so make that counter+1 and also for the input 5
1
3
4
2
5
5
your output is 1 and 4
3 and 2 but the output should be 1 and 4,2 and 3 so do that if(num1<num2) then print num1 and num2 else num2 and num1

1 Like

you can also have another approach to this question that first sort the array and then take two variables left =0th position of the array and right =last position of the array,then while(left<right) see if a[left]+a[right]==sum then print a[left] and [right] else if a[left]+a[right]<sum then do left++ else do right–

Hi @akshay9009
As you are not responding to the thread, I am marking your doubt as resolved for now. Re-open it if required.

Please mark your doubts as resolved in your course’s “Ask Doubt” section, when your doubt is resolved.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.