Linear Search Algorithm!! What is it?
It just a simple method to find out a given number into our given array or not?First of all, let's take a function called search(){} okay?
Second is our Main Function(){}?
Now, We know everything from the beginning of the Question, Just you need to implement it
into your code.
One more point to understand this code: here -1 Means out of our boundary / or Doesn't exit
#include <iostream>
using namespace std;
//Now it's our search function
//passing through this function is parameter given array[] it's given in the main function
//if the size of the array given, then replace n to a given size
// and passing int x=? where justifying is the number exists in our given array or not
int search (int arr[], int n, int x)
{
int i;
for(i=0;i<n;i++)
if (arr[i]==x)
return i;
return -1; // i already told about this minus means
// this whole function is returning index value i or -1
}
int main(void){
int arr[]={2,3,4,10,40,50};
int x=10;
int n=sizeof(arr)/sizeof(arr[0]);
int result=search(arr,n,x); // index value i stored in the result
(result==-1)? //Exits!!
cout<<"element is not in the array":cout<<"element in the present\n"<<result;
return 0;
}
Summary of this Code:
You need to know only two things on this code :
1.One "For" loop which is checking
2."If "condition, the Number is exited or not
But WHAT IF THE ARRAY WAS A RANDOM ONE!!! WHAT IF THE ARRAY BEEN CREATED AND YOU TOLD YOUR FRIEND ENTER A NUMBER, WHICH GONNA TELL HIM THAT'S NUMBER WAS IN YOUR ARRAY OR NOT!! IN OTHER WORDS, EVERYTHING WILL BE KNOWN AND UNKNOWN BY CODER!! HOW TO IMPLEMENT THOSE CODE?? Let's TRY YOURSELF...
Comments
Post a Comment