How to find all pairs in an array that equal to a given sum in C#

1 Answer

0 votes
using System;

public class Program
{
	public static void findAllPairs(int[] arr, int sum)
	{
		bool found = false;
		for (int i = 0; i < arr.Length - 1; i++) {
			for (int j = i + 1; j < arr.Length; j++) {
				if (arr[i] + arr[j] == sum) {
					Console.WriteLine("arr[" + i + "](" + arr[i] + ") + " + "arr[" + j + "](" + arr[j] + ")");
					found = true;
				}
			}
		}
		if (!found) {
			Console.WriteLine("Pair not found");
		}
	}

	public static void Main(string[] args)
	{
		int[] arr = new int[] {2, 4, 1, 5, 6, 8, 1};
		int sum = 10;

		findAllPairs(arr, sum);
	}
}




/*
run:
 
arr[0](2) + arr[5](8)
arr[1](4) + arr[4](6)
 
*/

 



answered Oct 10, 2022 by avibootz
edited Apr 16, 2023 by avibootz

Related questions

1 answer 182 views
1 answer 163 views
1 answer 149 views
1 answer 208 views
1 answer 176 views
...