C# Program to Perform Searching using Predefined Functions

«
»

This is a C# Program to perform searching using predefined functions.

Problem Description

This C# Program Performs Searching using Predefined Functions.

Problem Solution

Here the string is sorted using the predefined function using sort().

advertisement
Program/Source Code

Here is source code of the C# Program to Perform Searching using Predefined Functions. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Perform Searching using Predefined Functions
 */
using System;
class linSearch
{
    public static void Main()
    {
        Console.WriteLine("Enter Number of Elements you Want to Hold in the Array? ");
        string s = Console.ReadLine();
        int x = Int32.Parse(s);
        int[] a = new int[x];
        Console.WriteLine("Enter Array Elements :");
        for (int i = 0; i < x; i++)
        {
            string s1 = Console.ReadLine();
            a[i] = Int32.Parse(s1);
        }
        Array.Sort(a);
        Console.WriteLine("Sorted Array : ");
        for (int i = 0; i < x; i++)
        {
            Console.WriteLine("{0}", a[i]);
        }
        Console.WriteLine("Enter the Element to be Searched : ");
        string s3 = Console.ReadLine();
        int x2 = Int32.Parse(s3);
        int x3 = Array.BinarySearch(a, (Object)x2);
        Console.WriteLine("BinarySearch: " + x3);
        Console.WriteLine("Element {0} is {1}", x3, a[x3]);
        Console.Read();
    }
}
Program Explanation

In this C# program, we are reading the number of elements in the array using ‘x’ variable. Using for loop we are entering the coefficient values of an array using a[] array variable.

advertisement

Using the sort() function the string is sorted. We are reading the element to be searching using ‘s3’ variable. Using BinarySearch() function we are searching a required element. Print the searched string in the given string.

Runtime Test Cases
 
Enter Number of Elements you Want to Hold in the Array ? 5
Enter Array Elements : 
2
3
1
4
5
Sorted Array :
1
2
3
4
5
Enter the Element to be Searched : 4
Binary Search : 3
Element 3 is 4

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

advertisement
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn