w3resource

C#: Check a specified number is present in a given array of integers

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:

C# Sharp: Basic Algorithm Exercises - Check a specified number is present in a given array of integers.

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: Flowchart: Check a specified number is present in a given array of integers.

For more Practice: Solve these Related Problems:

  • Write a C# program to check if the specified number appears at both the beginning and end of an integer array.
  • Write a C# program to determine whether a number appears at least twice in a given array of integers.
  • Write a C# program to check if a given number is present at an index divisible by 3 in an array.
  • Write a C# program to check if a number appears consecutively in an array at least once.

Go to:


PREV : Count Substring Matching Last Two Characters.
NEXT : Element in First 4 Positions of Array.

C# Sharp Code Editor:



Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.