page5 q2

 avatar
Sameh
c_cpp
2 months ago
590 B
2
Indexable
Never
#include <iostream>
#include <ctime>

using namespace std;

int linearSearch(int * arr , int n , int key)
{
    for(int i = 0 ; i < n ; i++)
    {
        if(arr[i] == key)
            return i;
    }
    return -1;
}

int main()
{
    int arr[100];
    srand(time(NULL));
    for(int i = 0 ; i < 100 ; i++)
    {
        arr[i] = rand() % 101;
    }
    int key;
    cin >> key;
    int result = linearSearch(arr , 100 , key);
    if(result == -1)
        cout << "Number is not in array\n";
    else
        cout << "Number in index in " << result << "\n";
}
Leave a Comment