C# program to determine if any two integers in array sum to given integer
To determine if any two integers in an array sum to a given integer in C#, you can use a nested loop to compare each pair of integers. Here's an example program that checks if any two integers in the array sum to a given integer:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 2, 4, 6, 8, 10 };
int targetSum = 12;
bool exists = CheckPairSum(numbers, targetSum);
if (exists) {
Console.WriteLine("There exist two integers that sum to " + targetSum + ".");
}
else {
Console.WriteLine("No two integers found that sum to " + targetSum + ".");
}
}
public static bool CheckPairSum(int[] nums, int target) {
for (int i = 0; i < nums.Length; i++) {
for (int j = i + 1; j < nums.Length; j++) {
if (nums[i] + nums[j] == target) {
return true;
}
}
}
return false;
}
}
In this program, we have an array of integers called numbers and a target sum. We use the CheckPairSum method to determine if any two integers in the array sum to the target sum. The method uses a nested loop to compare each pair of integers. If the sum of any two integers equals the target sum, the method returns true. Otherwise, it returns false.
The program outputs whether there exist two integers in the array that sum to the target sum or not.
For example, with numbers = { 2, 4, 6, 8, 10 } and targetSum = 12, the program will output:
There exist two integers that sum to 12.
In this case, the pair of integers 2 and 10 in the array sums to the target sum of 12.