Exam 6 - Question 4 (c)

 avatar
itsLu
c_cpp
2 months ago
596 B
1
Indexable
Never
#include <iostream>
#include <ctime>
using namespace std;

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

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