-->




Linear search in C++ Program Example Code

7 comments
Linear search or sequential search is one of the searching algorithm in which we have some data in a data structure like array data structure and we have to search a particular element in it which is know as key.
By traversing the whole data structure elements from start to end one by one to find key comparing with each data structure element to the key.

In case of an array we check that the given key or a number is present in array at any index or not by comparing each element of array

There can be two possible outcomes if we are assuming that data structure like array contains unique values.


  • Linear search successful Key Found means in array at an index we found value which matches to our key
  • Linear search failed to find the Key mean our key does not exist in data


Linear Search in C++ Program Example Code


#include<iostream>
using namespace std;

int main() {

cout<<"Enter The Size Of Array:   ";
int size;
cin>>size;


int array[size], key,i;


// Taking Input In Array

for(int j=0;j<size;j++){
cout<<"Enter "<<j<<" Element: ";
cin>>array[j];
}

//Your Entered Array Is

for(int a=0;a<size;a++){
  cout<<"array[ "<<a<<" ]  =  ";
  cout<<array[a]<<endl;
}

cout<<"Enter Key To Search  in Array";

cin>>key;

 for(i=0;i<size;i++){

  if(key==array[i]){
cout<<"Key Found At Index Number :  "<<i<<endl;
break;
  }
}


if(i != size){

cout<<"KEY FOUND at index :  "<<i;
}
else{
cout<<"KEY NOT FOUND in Array  ";
}
   return 0;
}



Image View Of Code:
What is Linear or sequential in Search  C++ Program Example Code
What is Linear or sequential in Search  C++ Program Example Code using array



Sample Output:
Sample output What is Linear or sequential in Search  C++ Program Example Code
What is Linear Search In C++ Code Example Sample Output


Code Logic Explanation:

  • To Make Logic First We Think That We Have To Traverse Whole Array Form Start To End So we Decide To Use a Loop 
  • First for Loop Taking Input in Array Element By Element Second Displaying Entered Elements
  • Third for Loop Which is Main For Loop Having an if Condition Which Checks Every Array Element with Key
  • If an Element Matches With Key if Condition Becomes True and Loop Terminates With Break Statement
  • Then If Condition Outside Loop Which Will Become True Because Loop Variable 'i' not Equal to Size Of Array 
  • If Element Not Found In Array Than Loop Will Run Complete And If Condition Will Not True Because in This Case Loop Will Run Complete And After Termination Variable 'i' Will be Equal to Size Variable


Dry Running The Code With Sample Input
Let size=5;

Array Elements are
1
2
3
4
5

Key is equal to 4
3rd for loop comparisons

i=0
if(1==4) false

i=1
if(2==4) false

i=2
if(3==4) false

i=3
if(4==4) True
break for loop

Output:
Key Found At Index Number :  3

7 comments:

  1. good
    but we can replace the last if
    if(i != size){
    cout<<"KEY FOUND at index : "<<i;
    }
    else{
    cout<<"KEY NOT FOUND in Array ";
    }


    by this one
    if(i == size){
    cout<<"KEY NOT FOUND in Array ";
    }

    it will be better

    ReplyDelete
    Replies
    1. No, you can't do that. Consider the size = 1, and I=1 when it found the matching number - there would be an error. Instead, you can write something like this:

      #include
      #include

      using namespace std;

      int main()
      {
      int a[10], i, c, z=0;

      cout<<"Array can support up to 10 numbers.";
      cout<<"Please, enter the numbers";

      for(i=0;i<10;i++)
      {
      cin>>a[i];
      }

      cout<<"Enter the number you want to search";
      cin>>c;

      for(i=0;i<10;i++)
      {
      if (c==a[i])
      {
      z=c;
      cout<<"The number has been found at:"<<i;
      }
      }

      if (!(z==c))
      cout<<"The number wasn't found, sorry!";

      getch();
      }

      Delete
    2. Made a mistake right there, please, do not set the z=0 - because in that case if user input c=0, then it won't output the last value. Since, the compiler will assign a garbage value - the z will never be equal to c, unless the number has been found in the loop. So here's the most correct version.

      #include
      #include

      using namespace std;

      int main()
      {
      int a[10], i, c, z;

      cout<<"Array can support up to 10 numbers.";
      cout<<"Please, enter the numbers";

      for(i=0;i<10;i++)
      {
      cin>>a[i];
      }

      cout<<"Enter the number you want to search";
      cin>>c;

      for(i=0;i<10;i++)
      {
      if (c==a[i])
      {
      z=c;
      cout<<"The number has been found at:"<<i;
      }
      }

      if (!(z==c))//i will be incremented till 10 if the number isn't found through whole array.
      cout<<"The number wasn't found, sorry!";

      getch();
      }

      Delete


  2. You will be given a txt file, similar to OpeInFile.txt in Doc Sharing. The file has only one calculation per line. Notice that number of lines in the file is not known. You need to write your program to read each line and write the question and answer into another line.
    There are six main math operations: plus, minus, times, divided by, Min, Max. However plus, minus, times, and divided by can be expressed with signs also.
    For instance, if the input file has only these lines

    12 + 56
    9 divided by -3
    45 minus 15
    Min of 2 and 1
    Max of 3 and 5
    34 plus 33

    Your output file will be

    12 + 56 = 68
    9 / -3 = -3
    45 - 15 = 30
    Min (2, 1) = 1
    Max (3, 5) = 5
    34 + 33 = 67


    Note that the number of lines (operations) in the source txt file is not known.

    The name of output file will be CalculationResults.txt.

    ReplyDelete
  3. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Love from

    ReplyDelete
  4. Awesome. I am a beginner and this article helped me to resolve the problem .Thank you author and the whole expect team.

    http://www.wikitechy.com/view-article/linear-search-program-in-java-with-example-and-explanation


    Both are really good,
    Cheers,
    Venkat

    ReplyDelete