Ask Question
9 September, 19:02

Implement a function which takes as input an array and a key and updates thearrayso that all occurrencesof the input key have been removed and the remaining elements have been shifted left to fill the emptied indices. Return the number of remaining elements. There are no requirements as to the values stored beyond the last valid element.

+2
Answers (1)
  1. 9 September, 21:18
    0
    The function in cpp language is given.

    void shift (int n[], int num)

    {

    / / integer variable to keep count of remaining elements

    int count=10;

    for (int j=0; j<10; j++)

    {

    / / key element is compared to each element in the array

    if (n[j] = = num)

    {

    n[j] = n[j+1];

    / / decremented after each occurrence of key element in the array

    count--;

    }

    }

    std::cout<
    }

    1. The method accepts two parameters, one array and one element.

    2. The integer array, arr, and integer element, key, passed to this function are declared outside all the methods.

    3. The integer variable, count, is initialized to the size of the integer array, i. e., count contains the number of elements present in the array, arr.

    4. Inside the for loop, the element is compared with each element in the array. If they match, the integer variable, count, is decremented each time the element occurs in the array.

    5. After the loop completes, the number of remaining elements are displayed.

    This function is implemented inside a cpp program as shown below.

    #include

    #include

    / / integer array declared and initialized

    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 2, 8, 2};

    / / element to be removed from the array

    int key = 2;

    void shift (int n[], int num)

    {

    / / integer variable to keep count of remaining elements

    int count=10;

    for (int j=0; j<10; j++)

    {

    if (n[j] = = num)

    {

    n[j] = n[j+1];

    count--;

    }

    }

    std::cout<
    }

    int main ()

    {

    / / function called having array and key as parameters

    shift (arr, key);

    return 0;

    }

    The program begins when the array and the element are declared and initialized at the beginning of the program.

    Inside the main () method, the method shift () is called by passing two parameters to this method.

    The main () method has return type of integer. Hence, this program ends with a return statement.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Implement a function which takes as input an array and a key and updates thearrayso that all occurrencesof the input key have been removed ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers