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

write with C++ *(the course uses Visual Studio 2012) Write a function that recei

ID: 3806259 • Letter: W

Question

write with C++

*(the course uses Visual Studio 2012)

Write a function that receives an integer array, the length of the array, an integer for indicating the position, an integer for insertion) and returns a Boolean value (True or False). Using following function header:

bool insert(int a[],int length, int position, int item)

{

...

}

The function will shift all the numbers from “position” in the array to the right by one place and replace the number in the “position” by “item” If “position” > “length” or “position” < 1 the function returns false, otherwise the function returns true.

For example, if the function receives following array: myArray[7]={1,2,3,4,5,6,7}, and position=3, item=100, then after the function call, the array would be containing following numbers: {1,2,100,3,4,5,6}.

Explanation / Answer

#include <iostream>
using namespace std;

// function starts here
bool insert(int a[],int length, int position, int item)
{
// checking whether the position is valid or not
// if not, it stops here and returns false
if(position<1 || position>length)
return false;
  
// saving the value in temp and using later
int temp = a[position-1], temp1;
a[position-1] = item;
  
// for each position, shifting by 1 to right
for(;position<length;position++);
{
temp1 = a[position];
a[position] = temp;
temp=temp1;
}
  
// printing the array
for(position = 0;position<length;position++)
cout << a[position] << " ";
return true;
}
int main()
{
// for testing
int myArray[7]={1,2,3,4,5,6,7};
cout << endl << "Returned "<< insert(myArray, 6, 3, 100) << endl;
return 0;
}

/* Sample output

1 2 100 4 5 6                                           

Returned 1

*/