Originally Posted by
joh23
hello there! can anyone help me with this could code.any suggestions and ideas will be very much appriciated.
Code:
int insB4Odd(int LA[],int n,int num){
/* This function inserts item num b4 the index position
of the first odd integer in the array list LA w/ n elements */
int j=0;
while(j<n){
if(LA[j]%3==0)
/* This is the part where i'm stuck*/
}
return(++n);
}
Your test for oddness would classify six and twelve as odd numbers! A number is odd if it is not even so a good test is number % 2 != 0. Once you have found the place where you want to insert the new element, you need to make room for it. You can do this by using the memmove function to move all the subsequent elements forward.
Code:
int insAftrEven(int LA[],int n,int num){
/* This is somewhat the same with the above function,but instead
of inserting b4 odd,item num is inserted after even number in the
array list */
int j=0;
while(j<n){
if(LA[j]%2==0)
/*I'm also stuck here.If I can just get the B4Odd,
there's gonna be no problem here */
}
return (++n);
}
Yes, again use memmove to make room for your new element. I suggest you create a common insertion function that can be used by both insB4Odd and insAftrEven.
Code:
int delNum(int LA[],int n,int num){
/* deletes the integer num from the array list LA if it exists,
otherwise no deletion is made*/
int i;
for(i=0;i<n;i++){
if(LA[i]==num)
/*What would be the next part?*/
}
return (--n);
}
You can delete an element by moving all the subsequent elements back one position. Again memmove is the function to use.
Code:
int delAll(int LA[],int num){
/* deletes all items that are not unique */
Just give me an idea on how to go about this function.
There are two approaches for finding duplicates. The first is for every element in the array search every other element searching for matches. This would be done with a nested loop. The other, more efficient, approach is to first sort the array and then walk through it looking for adjacent elements that are equal. You can sort an array with qsort. The caller of this function may not want the order of the array changed. In this case, you could use the first approach (simpler) or create a temporary array to find the duplicates and only alter the original to delete the required elements. Once you've found an element to delete, again you can use memmove. You could create a common delete function to be used by both this function and delNum.
Note that I have formatted your code. Properly formatted code is far easier to read and update.
Some things you should think about are:
- Is there room in the array to add an element. This is probably a concern to the caller rather than your functions.
- What happens if there are no even/odd/duplicate numbers in the array. Will the code fail or return an incorrect value?
Good luck, if you need anymore specific help, please post back.