Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Suppose we are given n array a of non-negative integers of length n, that is, we

ID: 3833420 • Letter: S

Question

Suppose we are given n array a of non-negative integers of length n, that is, we are using slots 0 through n-1 as usual. As an example, suppose n = 20, and a[0..19] = 14 71 2 11 19 7 1 3 56 91 4 0 5 0 0 10 9 0 33 67 Think of the zero entries as representing empty slots and positive entries as representing occupied slots in the array. Write a function Void shift (int num, int a[], int a) which takes a positive integer num and inserts it into array slot 0 by shifting entries one slot right to make room as needed. An example (using the above array) follows: If we wanted to insert the number 20 slot into slot 0 array (occupied by the number 14), we would have to shift all the numbers in slot 0 through 10 one slot to the right(slot 11 is the first empty slot) to make room for the new entry. The resulting array should look like: a[0..19] = 14 71 2 11 19 7 1 3 56 91 4 0 5 0 0 10 9 0 33 67 [important programming notes: (a). If the array is completely full (all n slots are occupied), your function should output a message to that effect, and not do the insertion, (b). Recall that arrays in C++ are passed by reference, so (if the array is not full) your function can and should change the array contents when does it does the insertion, and it should report that insertion was successful; it need not display the updated array.]

Explanation / Answer

#include <iostream>
using namespace std;
void shift(int num, int a[], int n)
{
    int i;
    for(i = 0; i < n; i++)   //Starting from slot zero till the end of array.
        if(a[i] == 0)   //If you found an empty slot.
            break;       //Stop moving further.
    if(i == n)   //If there are no empty slots.
        cout << "There is no empty slot to insert. Sorry..." << endl;
    else   //If found a slot.
    {
       for(; i > 0; i--)   //Starting from empty slot, moving down to the start of the array.
           a[i] = a[i-1];   //Pull the just previous element to the right.
       a[0] = num;   //Now, put the new value at the start of the array.  
       cout << "Element inserted successfully." << endl; //Reporting a successful insertion.
    }          
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote