C#: Check a specified number is present in a given array of integers
C# Sharp Basic Algorithm: Exercise-32 with Solution
Check if Element Present in Array
Write a C# Sharp program to check if a specified number is present in a given array of integers.
visual Presentation:
Sample Solution:-
C# Sharp Code:
using System;
using System.Linq;
// Namespace declaration
namespace exercises
{
// Class declaration
class Program
{
// Main method - entry point of the program
static void Main(string[] args)
{
// Calling the 'test' method with different arrays and integer inputs
Console.WriteLine(test(new[] {1,2,9,3}, 3)); // Output: True
Console.WriteLine(test(new[] {1,2,2,3}, 2)); // Output: True
Console.WriteLine(test(new[] {1,2,2,3}, 9)); // Output: False
Console.ReadLine(); // Keeping the console window open
}
// Method to check if an integer array contains a specific integer
public static bool test(int[] numbers, int n)
{
// Using LINQ's 'Contains' method to check if the array 'numbers' contains the integer 'n'
if (numbers.Contains(n)) // If 'n' is found in the array 'numbers'
return true; // Return true
return false; // If 'n' is not found in the array 'numbers', return false
}
}
}
Sample Output:
True True False
Flowchart:
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to count a substring of length 2 appears in a given string and also as the last 2 characters of the string.Do not count the end substring.
Next: Write a C# Sharp program to check if one of the first 4 elements in an array of integers is equal to a given element.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/csharp-exercises/basic-algo/csharp-basic-algorithm-exercises-32.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics