C# program to check if array contains a duplicate number
To check if an array contains a duplicate number in C#, you can use a HashSet to keep track of the numbers encountered so far. Here's an example program that checks if an array contains a duplicate number:
using System;
using System.Collections.Generic;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 1, 2, 3, 4, 5, 2, 6, 7, 8 };
bool containsDuplicate = CheckDuplicate(numbers);
if (containsDuplicate) {
Console.WriteLine("The array contains a duplicate number.");
}
else {
Console.WriteLine("The array does not contain any duplicate numbers.");
}
}
public static bool CheckDuplicate(int[] nums) {
HashSet seenNumbers = new HashSet();
foreach (int num in nums) {
if (seenNumbers.Contains(num)) {
return true; // Duplicate number found
}
seenNumbers.Add(num);
}
return false; // No duplicate number found
}
}
In this program, we have an array of integers called 'numbers'. We use the 'CheckDuplicate' method to check if the array contains a duplicate number. The method utilizes a HashSet, 'seenNumbers', to keep track of the numbers encountered so far. For each number in the array, it checks if the number is already present in the HashSet. If it is, the method returns 'true', indicating the presence of a duplicate number. Otherwise, it adds the number to the HashSet and continues iterating. If no duplicate is found, the method returns 'false'.
The program outputs whether the array contains a duplicate number or not.
For example, with 'numbers = { 1, 2, 3, 4, 5, 2, 6, 7, 8 }', the program will output:
The array contains a duplicate number.
In this case, the number '2' appears twice in the array, indicating the presence of a duplicate number.