Input: An integer (intVal) and an array of n (n>0) increasing integers (a[]) Out
ID: 3590751 • Letter: I
Question
Input: An integer (intVal) and an array of n (n>0) increasing integers (a[])
Output: + Insert the integer intVal into the array a[], after inserting the array a[] is still increasing. + Print the array a[] on the “stdout”
Note: + The code for the inserting MUST be implemented using a function with passing by REFERENCE + You do NOT need to check if the input array is increasing. It is ALWAYS increasing. + Do not insert the intVal if it is already in the array a[]
Hint: You should create a function for the inserting as the following int insertVal(int[] a, int intVal, int *n) where n is the length of the array a[], the function should return 1 if intVal is inserted, -1 otherwise
Sample input/output: + Input: 2 lines - Line 1 is for intVal: an integer (no other character) - Line 2 is for a[]: a list of increasing integers separated by a comma, no whitespace at all + Output: the list of increasing integers separated by a comma
input: 5
1,2,7
output: 1,2,5,7
Explanation / Answer
int insertVal(int[] a, intVal, int n)
{
int b[n];
int j = 0;
/* find function returns 1 if found and 0 if not found */
/* we have to insert if the intVal is not in the array */
if( find(a,intVal,n) == 0 )
{
int i;
int flag = 1;
/* looping over array to insert value */
for(i = 0; i<n; i++)
{
b[j] = 0;
if(a[i] > intVal )
{
/* copying the variables of a to b */
b[i] = a[i];
/* inserting intVal at the position */
a[i] = intVal;
}
}
/* looping again to copy the values after the inserted value in a*/
for(j = 0; j<n; j++)
{
if(a[j] == intVal)
{
a[j+1] = b[j];
}
}
return 1;
}
return -1;
}
int find( int a[], int intVal, int n )
{
int i =0;
for( i = 0; i<n; i++ )
{
if(a[i] == intVal)
return 1;
}
return 0;
}
/* this is the insertVal() function.
I have used one more method to find if array has the given number or not */
/* If any queries please comment */