Hello again!
I'm still working hard on some exam practice preparation and I'm having some trouble searching an array in my program. I was able to search an array before with a linear search, so that is what I'm trying to put into this overall program, but things are just not simply working out. I've been confronted by a large number of errors and I cannot determine where the main cultprit of such output is. I'd be happy to post the errors if requested, but the problem seems to be lying somewhere in linearSearch or something to do with SIZE. In the original linear search code that I am basing this program off of, SIZE is defined, but would I need to do that if I already defined the array?
The goal I'm working towards is prompting the user to imput a value and to search the array to find the value. If it is found, then the function will return the location of the value, but if not, it should return -1.
Code:
#include <stdio.h>#include <stddef.h>
#include <stdlib.h>
#include <time.h>
void display(int testArray[]);
void randPop(int testArray[]);
size_t linearSearch(const int testArray[], int key, size_t size);
int main()
{
int min, i, position;
int testArray [5] = {22, 3, 5, 707, 1};
printf("Enter integer search key: ");
int searchKey;
scanf("%d", &searchKey);
size_t index = linearSearch(testArray, searchKey);
if (index != -1)
{
printf("Found value at index %d\n", index);
}
else
{
puts("Value not found.");
}
srand((unsigned int)time(NULL));
display(testArray);
randPop(testArray);
min = testArray[0];
for(i = 1; i < 5; i++)
{
if(min > testArray[i])
{
min = testArray[i];
}
}
printf("The smallest integer of the array is: %d\n", min);
return 0;
}
void display(int testArray[])
{
for (size_t i = 0; i < 0; ++i) {
printf("%7zu%13d\n", i, testArray[i]);
}
}
void randPop(int testArray[])
{
for (size_t i = 0; i < 5; ++i) {
testArray[i] = rand() % 100 + 1;
printf("%7zu%13d\n", i, testArray[i]);
}
}
size_t linearSearch(const int testArray[]; int key, size_t size)
{
for (size_t n = 0; n < size; ++n)
{
if (testArray[n] == key)
{
return n;
}
}
return -1;
}
Thank you for all help in advance. Finals are such a stressful time! I'd like to be as prepared as possible, but it seems like this stress is making me lose my mind!
Best!