Friday, November 29, 2013

P3C4: C Sharp Program for Linear search or Serial search

//Source Code
using System;

public class Program_Linear_Search
{
    int linear_search(int[] a, int size, int item)
    {
        int i = 0;
        while(i<size && a[i]!=item)
            i++;

        if(i<size)
            return i; //returns index number of the item in the array
        else
            return -1; //item doesn't present in the array
    }
     
    public static void Main()
    {
     
        int[] b = new int[] {2,4,5,7,8,9,12,15};
        int size=8, item;
     
        Console.WriteLine("Enter a number to search: ");
        item =Convert.ToInt32(Console.ReadLine());


        Program_Linear_Search pls = new Program_Linear_Search();
        int p = pls.linear_search(b, size, item);
     
        if (p ==-1)
            Console.WriteLine("\n{0} is not present in the array", item);
        else
            Console.WriteLine("\n{0} is present in the array at index no: {1}", item, p);

        Console.WriteLine("\nPress any key to exit...");
        Console.ReadLine();
    }
}

OUTPUT

Enter a number to search:
5

5 is present in the array at index no: 2

Press any key to exit...

No comments:

Post a Comment