Exam 6 - Question 4 (c)

 avatar
itsLu
c_cpp
a year ago
596 B
3
Indexable
#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