How to search in array in C++

0

  In this article we will discuss linear search in java. Searching is an operation in the array through which we find whether an element is present in the array or not. If the element is present in the array then we return the index of that number and if the number is not present in the array in that case we return -1 as output . So lets take an example and see how things goes.



Input : [ 1, 2, 3, 4, 5, 6] , number : 6

Outut : 5


Input : [ 1, 2, 3, 4, 5, 6] , number : 55

Outut : -1


nput : [ 1] , number : 6

Outut : -1


Steps:

1. We are given an array and a number.

2. First we run a for loop over array elements

    i. We take i=0 and compare if ith element is equal to the given number.

    ii. If ith number is equal to that given number  then return i

    iii. Else move to the next element

3. If no ith element is equal to given number then in that case return -1


CPP Code :



//This code is written by hindi coding community
#include <iostream>
using namespace std;
int main()
{
int input[100], count, i, num;
cout << "Enter Number of Elements in Array\n";
cin >> count;
for(i = 0; i < count; i++){
cin >> input[i];
}
cout << "Enter a number to serach in Array\n";
cin >> num;
for(i = 0; i < count; i++){
if(input[i] == num){
cout << "Element found at index " << i;
break;
}
}
if(i == count){
cout << "Element Not Present in Input Array\n";
}
return 0;

}


Time Complexity : O(n)

Space Complexity : O(1)


If you want to write for us then please contact us at hindicodingcommunity@gmail.com




Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !