programing with arrays in C++ implement your own functions for arrays and test t
ID: 3686033 • Letter: P
Question
programing with arrays in C++
implement your own functions for arrays and test then in the main. Do not use pointer or <string> libray.
include <iostream> and namespace std only.
int ShiftLeft( );
int ShiftRight( );
int InsertBefore( );
int InsertAfter( );
main()
{
int array[] = {1,2,3,4,5};
return 0;
}
int ShiftLeft( ) //Shift items left starting at pos, return fail code
{
}
int ShiftRight( ) //Shift items right starting at pos, return fail code
{
}
int InsertBefore( )//insert an element before element number n, return fail code
{
}
int InsertAfter( ) //Insert an element after element number n, return fail code
{
}
Explanation / Answer
#include <iostream>
using namespace std;
int ShiftLeft( int [], int, int);
int ShiftRight( int [], int, int);
int InsertBefore( int[], int, int, int);
int InsertAfter( int[], int, int, int );
void printArray(int[], int);
int main()
{
int array[] = {12,22,31,44,55};
int size = 5;
printArray(array, size);
ShiftLeft(array, 2, size);
printArray(array, size);
ShiftRight(array, 2, size);
printArray(array, size);
InsertBefore(array, 2, size, 100);
printArray(array, size);
InsertAfter(array, 1, size, 199);
printArray(array, size);
return 1;
}
int ShiftLeft(int arr[], int pos, int size) //Shift items left starting at pos, return fail code
{
if(pos>=size||pos<0)
return -1;
int pos_element = arr[pos];
for(int i=pos;i<size-1;i++)
arr[i] = arr[i+1];
arr[size-1] = pos_element;
return 1;
}
int ShiftRight(int arr[], int pos, int size ) //Shift items right starting at pos, return fail code
{
if(pos>=size||pos<0)
return -1;
int last_element = arr[size-1];
for(int i=size-1;i>pos;i--)
arr[i] = arr[i-1];
arr[pos] = last_element;
return 1;
}
int InsertBefore( int arr[], int pos, int size, int value)//insert an element before element number n, return fail code
{
if(pos>=size||pos<0)
return -1;
ShiftRight(arr, pos, size);
arr[pos] = value;
return 1;
}
int InsertAfter( int arr[], int pos, int size, int value) //Insert an element after element number n, return fail code
{
if(pos>size)
return -1;
ShiftRight(arr, pos+1, size);
arr[pos+1] = value;
}
void printArray(int arr[], int size)
{
for(int i=0;i<size;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.