linearsearch1
Copy the following code into a file called linearsearch1.c.
#include<stdio.h> #include<stdlib.h> int linearSearch(int * a, int key, int size) // returns the index of key in the array a or -1 if key is not found { int i = 0, pos = 0, found = 0; while (!found && (i<size)) { if (a[i] == key) { found = 1; pos = i; } else i++; } return found ? pos : -1; } main() { int N; /* how many numbers? */ int * nums; /* where are they ? */ int i; /* loop counter */ int key; /* key to find */ int result; /* result of search */ char option; /* what the user wants to do */ // Find out how many numbers are needed and dynamically allocate an array printf("How many numbers? "); scanf(" %i", &N); nums = malloc(N * sizeof(int)); // Input the numbers one at a time from the standard input stream for (i=0; i<N; i++) { printf("nums[%d] ? ", i); scanf(" %i", &nums[i]); } // What would the user like to do? printf("Option: (f)ind number or (q)uit?"); scanf(" %c", &option); while (option != 'q') { printf("Value to look for? "); scanf(" %i", &key); result = linearSearch(nums,key,N); if (result != -1) printf("Found %d at position %d\n", key, result); else printf("Key %d not found\n", key); printf("Option: (f)ind number or (q)uit?"); scanf(" %c", &option); } }
Compile and run the program and make sure that you understand how it works. Note particularly the following points:
- The use of the found flag in the linear search function. You should dry run this code on paper to check that you understand fully how it works.
- The main program allocates memory for an array dynamically. This means that the memory is allocated at run-time rather than at compile-time. The reason for this is that you do not know until the user enters the size of the array how big it must be. Dynamic memory allocation is covered a little later in the module (and in more depth) but if you wish to read ahead you should look at how the function malloc works.
- The main body of the program is a fairly straightforward loop that asks the user to enter a command and then responds. Please make sure you are happy with how this is working because this main program will be used as a basis and developed in a number of ways during subsequent exercises and over the next few weeks.