Ask Question

Create a method to search an un-ordered array of integers for a value, if the value is found return the index of its position in the array, if not found, return - 1.

+2
Answers (1)
  1. 16 June, 05:50
    0
    Following are the program in C+ + language

    #include / / header file

    using namespace std; / / namespace

    int search (int s[], int s1, int n) / / function search

    {

    for (int k = 0; k
    {

    if (s[k] = = s1) / / searching the element

    {

    return (k); / / return the index

    break;

    }

    }

    return (-1); / / return (-1)

    }

    int main () / / main function

    {

    int arr[100], n1, i, s; / / variable declaration

    cout<<"Enter number you want in the array:";

    cin>>n1;

    cout<<"Enter the elements in the array/n ";

    for (i = 0; i
    {

    cin>>arr[i]; / / taking input into the array

    }

    cout<<"Enter a number you want to search: ";

    cin>>s; / / read the serach element by the user

    int res = search (arr, s, n1); / / calling function search

    cout<
    return 0;

    }

    Output:

    Enter number you want in the array:3

    Enter the elements in the array

    1

    2

    34

    Enter a number you want to search: 2

    2

    Explanation:

    Following are the description of the program

    Read the number you want in array in the "n1" variable of int type. Read the array by the user in the "arr ". Read the searching element in the "s" variable. calling the function search by passing array arr, searching element "s" and "n1". In the search function, it returns the index of its position in the array, if not found then it return - 1. Finally print the index.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Create a method to search an un-ordered array of integers for a value, if the value is found return the index of its position in the array, ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers