C#: Check if a given number present in an array of numbers
Check Number in Array
Write a C# program to check if a given number is present in an array of numbers.
Sample Solution:
C# Sharp Code:
using System;
using System.Linq;
namespace exercises
{
class Program
{
// Main method where the program execution begins
static void Main(string[] args)
{
int[] nums = { 1, 3, 5, 7, 9 };
int n = 6;
// Calls the test function and prints the result
Console.WriteLine(test(nums, n));
n = 3;
// Calls the test function again with a different value of n and prints the result
Console.WriteLine(test(nums, n));
}
// Function to test if an array contains a specific element
public static bool test(int[] arra, int n)
{
// Uses the Contains method of LINQ to check if the array contains the given number 'n'
return arra.Contains(n);
}
}
}
Sample Output:
False True
Flowchart:

Sample Solution-1:
C# Sharp Code:
using System;
using System.Linq;
namespace exercises
{
class Program
{
// Main method where the program execution begins
static void Main(string[] args)
{
int[] nums = { 1, 3, 5, 7, 9 };
int n = 6;
// Calls the test function and prints the result
Console.WriteLine(test(nums, n));
n = 3;
// Calls the test function again with a different value of n and prints the result
Console.WriteLine(test(nums, n));
}
// Function to test if an array contains a specific element using a foreach loop
public static bool test(int[] arra, int n)
{
// Loop through each element in the array
foreach (int item in arra)
{
// Check if the current element matches the given number 'n'
if (item == n)
return true; // If found, return true immediately
}
return false; // If not found after checking all elements, return false
}
}
}
Sample Output:
False True
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C# program to check if a given number appears more than once in an array.
- Write a C# program to return the index of a given number if it appears exactly once in the array.
- Write a C# program to check whether all numbers from 1 to 10 are present in the array.
- Write a C# program to return true only if a number appears in both the first and second half of an array.
Go to:
PREV : Reverse Strings in Parentheses.
NEXT : Get File Name from Path.
C# Sharp Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.