CPE 101

Take Home Lab


This is an individual lab.
Write a program to read a list of positive integers, terminated by a zero, and displays the numbers in the order they were read but without duplicates.   You may assume there will be at most 100 numbers.

For example, an input of:
8 4 9 3 4 9 4 7 3 2 0
would display
8 4 9 3 7 2

This problem can be solved using a single array.  You may use the linear search function provided in the textbook (or the instructor's "classic" version of linear search).

You must decompose the solution into appropriate functions and choose looping constructs
best suited for the problem.

Document your solution clearly following the class coding standard. 

Name your source file "unique_ints.c" and submit your solution using handin to Lab10.




/* Take home lab - instructor solution */
#include 
#define MAX 100
#define NOT_FOUND -1  /* Value returned by search function if target not
found 	*/
/*
 *  Searches for target item in first n elements of array arr
 *  Returns index of target or NOT_FOUND
 *  Pre:  target and first n elements of array arr are defined and n>=0
 */
int
search(const int arr[],  /* input - array to search	*/
       int       target, /* input - value searched for	*/
       int       size)      /* input - number of elements to search	*/
{
      int index;         /* position in array */
      int where;         /*  index where target found or NOT_FOUND	*/

      /*  Compares each element to target	*/
      index = 0;
      while (arr[index] != target && index < size) 
      {
                ++index;
      }

      /* Did we find the target item? 	*/
      if (index == size)
      {
            where = NOT_FOUND;
      }
      return (where);
}

/* Write a program to read a list of positive integers, terminated by a
 * zero, 
 * and displays the numbers in the order they were read but without
 * duplicates. */
int main()
{
	int numbers[MAX] = {0};  /*  an array to store the numbers */
	int saved = 0;            /*  how many we've saved */
	int current;              /*  the current number */
	
	printf("Enter a list of positive integers, terminated by a zero: ");
	scanf ("%d",¤t);

    /* Read numbers until the sentinel is found */
	while (current != 0)
	{
        /* If this number hasn't be saved, then save and print it */
		if (search(numbers, current, MAX) == NOT_FOUND)
		{
			numbers[saved] = current;
			saved = saved + 1;
                        printf("%d ",current);		
		}
                /* Read the next number */
		scanf("%d", ¤t);
			
	}
	return (0);
}