C# Program to Search an Element in an Array
Posted by Superadmin on August 15 2022 13:59:40

C# Program to Search an Element in an Array

 

 

This is a C# Program to search an element in an array.

Problem Description

This C# Program Searches an Element in an Array.

Problem Solution

Here an array is declared and an element is searched and if found and displayed.

Program/Source Code

Here is source code of the C# Program to Search an Element in an Array. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Search an Element in an Array
 */
using System;
using System.IO;
class Program
{
    static void Main()
    {
 
        string[] array1 = { "cat", "dogs", "donkey", "camel" };
        string v1 = Array.Find(array1,
            element => element.StartsWith("cam", StringComparison.Ordinal));
        string v2 = Array.Find(array1,
            element => element.Length == 3);
        Console.WriteLine("The Elemnt that Starts with 'Cam' is : " +v1);
        Console.WriteLine("3 Letter word in the Array is : " +v2);
        Console.ReadLine();
    }
}
Program Explanation

In this C# program, we have already defined the value of ‘array1’ variable. Compute the find() function to find an element starts with ‘cam’ variable using ‘StringComparison.Ordinal’. It compares the strings based on the order of characters. Then another variable ‘v2’ is used to find the length of an element whose size is 3. Print the searched element in an array.

 
Runtime Test Cases
 
The Element that Starts With 'Cam' is : Camel
3 Letter Word in the Array is : cat