C#: Linear Searching using Arrays

In this C# tutorial we are  "developing a simple program which accepts number entered by the user and displays result if it is found in a single dimensional array" . Here we are taking variable "num" for number entered by the user and "arr" for initializing our array with five elements respectively. It asks user to enter a number , if the element found then it displays message "element found!!". For this we are using for loop here. Also you see in line 11 we have taken variable flag and initialized it with 0. If element is found then flag will be updated to 1, if its not then it will remain 0 as you see in line 47. Now, lets get started!!

using System;

​class prg

{

public static void Main(String []args)

{

  int flag=0;

  int []arr = {1,10,12,13,9,4}; //initialised array elements​

  int num; // variable for user​

  Console.WriteLine("Please enter number which you want to search");

  num=Convert.ToInt32(Console.ReadLine());

    for(int i=0;i<6;i++)

     {

        if(arr[i] == num)

        {

          Console.WriteLine("element found!!");

          flag=1;

        }

        else

        {

          Console.WriteLine("Searching!!!!!!!!!!!!!!!");

        }

        if(flag==1)break;

     }

    if(flag==0)

    {

     Console.WriteLine("Not Found.....");

    }

}

}
SHARE

Raunak Hajela

Hi. I’m CEO/Founder of Kodestat. I’m Student, Geek, Web Designer, Developer, Blog Enthusiast and Player. Inspired to make things looks better. I like playing with codes plus I am marvel fan :-P You can check my design portfolio here. For consulation fell free to drop an email at raunakhajela@gmail.com.

  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment