160k views
1 vote
1) write an insertfirst function for a partially filled array. this function should accept all required data as input parameters. example if an array contains 7,10,3,9,5 and the insertfirst function is called with a value of 20, the array will become 20,7,10,3,9,5.

User Yelisa
by
4.2k points

1 Answer

3 votes

So the Algorithm goes like this:

you need to pass the size of array , array and the value you need to insert at First in your function

Then you will increase the size by 1 and shifts every element of the array by 1 towards right

Then finally after shifting is done put the value at 0th index as the required value

int* InsertFirst(int n, int arr[], int x)
{
// increase the size by 1
n++;

// shift elements forward
for (int i = n-1; i >= 0; i--)
arr[i] = arr[i - 1];

// insert x at start position of array
arr[0] = x;

return arr;
}

User Ofer Helman
by
4.8k points