CSc 265 Lab4

For the code below, carefully examine each function and make sure that it conforms to its specification in the comment block above it, and that it does not violate the assumption given. If you find a fault in one of the functions, enter the line number on which the fault occured and give a brief description of the fault. Also check the code in the main() function for faults. *Note: do not suggest a fix for a bug, just briefly describe what is wrong.

    18	#include <stdio.h>
    19	
    20	/* if x is in a[0..n-1] then return its index else return -1
    21	*  Assume: n >= 0 and a has at least n elements
    22	*/
    23	int findpos(int a[],int n,int x)
    24	{
    25		int i;
    26	
    27		for (i = 0; i < n; i++)
    28			if (a[i] != x) return i;
    29		return -1;
    30	}
    31	
    32	/* Shift the elements of a[startpos+1..endpos] left one position
    33	*  Assume: 0 <= startpos < endpos < N,
    34	*	where N is the number of elements in a
    35	*/
    36	void shiftleft(int a[],int startpos,int endpos)
    37	{
    38		int i;
    39		
    40		for (i = startpos; i <= endpos; i++)
    41			a[i] = a[i+1];
    42	}
    43	
    44	/* Eliminate all values in a that are not in b.
    45	*  More precisely, modify a so that a[0..alen-1] contains only
    46	*  the values originally in a[0..alen-1] and also in b[0..blen-1].
    47	*  Change alen to reflect the new length of a.
    48	*/
    49	void intersection(int a[],int *alen,int b[],int blen)
    50	{
    51		int i;
    52	
    53		for (i = alen-1; i >= 0; i--) {
    54			if (findpos(b,blen,a[i]) != -1) {
    55				shiftleft(a,i,*alen-1);
    56				(*alen)--;
    57			}
    58		}
    59	}
    60	
    61	main()
    62	{
    63		int a[] = {1,3,5,7,9};
    64		int alen = 5;
    65		int b[] = {1,5,9};
    66		int blen = 3;
    67		int i;
    68	
    69		intersection(a,alen,b,blen);
    70		for (i = 0; i < alen; i++)
    71			printf("a[%d]: %d ",i,a[i]);
    72		printf("\n");
    73	}
    74	
    75	

Answers:

line 28:

The != comparison causes the function to return the index of the first array position which is NOT equal to x, or if a[0] == x, it returns -1.

line 40:

The <= in the loop termination condition is incorrect. The way it is written causes the elements of a[startpos+1..endpos+1] to be shifted one position to the left, instead of a[startpos+1..endpos].

line 53:

The variable i is initialized to alen-1 in the loop. This is incorrect since alen is a pointer, and must be dereferenced with the * operator to yield the desired value.

line 54:

The != comparison is incorrect. It causes the shiftleft() call on line 55 to be executed when a[i] is present in the array b[], rather than when it is absent, which is what we want.

line 69:

The second parameter to the intersection() function call is incorrect. intersection() expects a pointer (address) here, and alen is a value.