On collections of things, linear search is utilized. It is based on the approach of traversing a list from beginning to end by studying the attributes of all the components encountered along the route.
#include <stdio.h>
int search(int arr[], int N, int x)
{
int i;
for (i = 0; i < N; i++)
if (arr[i] == x)
return i;
return -1;
}
// Driver's code
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int x = 10;
int N = 5;
// Function call
int result = search(arr, N, x);
if (result == -1)
{
printf("Number is not found in array");
} else{
printf("Number is found at index %d", result);
}
return 0;
}
-------------with C++ --------------
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i, n, arr[100];
cout << "enter n :";
cin >> n;
for (i = 1; i <= n; i++)
{
cin >> arr[i];
}
int num, index;
cout << "enter number :";
cin >> num;
for (i = 1; i <= n; i++)
{
if (arr[i] == num)
{
index = i;
cout << num << " found in array index is " << index;
}
}
return 0;
}
Output
Number is found at index 3
0 Comments