Write a C program that creates an array of 500 integer elements and loads it wit
ID: 3911081 • Letter: W
Question
Write a C program that creates an array of 500 integer elements and loads it with each value equal to the subscript's square, and then write a sequential and a binary search algorithm to see whether a number is a perfect square. Use a loop to load the array. Prompt the user for a positive integer value less than 250,000. Test the functions by calling them from a simple interactive main() function using a menu, with different values used to select the choice of function. The program should contain a main() function and the following functions: 1- Void loadArray(int numsl], int size) To load the array nums with its subscript's squares 2- Int binarySearch(int numsl, int size, int key) To search the input array for a key using binary search approach and return the number of comparisons 3- Int sequentialSearch(int numsl, int size, int key) To search the input array for a jey using sequential search approach and return the number of comparisons Int getKey() To get a valid integer key (between 0 and 250,000) from the user to search 4- The program should contain a loop that permits users to enter a new choice of function for each loop, until exit from the loop explicitlyExplanation / Answer
Program
#include <stdio.h>
void loadarray(int[],int);
int binarySearch(int[],int,int);
int getKey();
int main()
{
int nums[5],x; //arrays of ints
loadarray(nums,5);
printf(" The array is : ");
for(x=0;x<5;x++)
printf("%d ",nums[x]);
int key=getKey();
int result = binarySearch(nums, 5, key);
if(result == -1)
{
printf("Element Not Found ");
}
else
{
printf("Element Found at Position %d ", result + 1);
}
key=getKey();
int position = sequentialSearch(nums, 5, key);
if (position == -1)
printf("%d isn't present in the array. ", key);
else
printf("%d is present at location %d. ", key, position+1);
return 0;
}
void loadarray(int nums[],int size) //header
{
int x; // subscript
for(x=0;x<size;x++)
{
nums[x]=x*x;
}
}
int getKey()
{
int k;
printf(" Enter key : ");
scanf("%d",&k);
return(k);
}
int binarySearch(int nums[],int size,int key)
{
int low = 0, high = size - 1, middle;
while(low <= high)
{
middle = (low + high) / 2;
if(key > nums[middle])
low = middle + 1;
else if(key < nums[middle])
high = middle - 1;
else
return middle;
}
return -1;
}
int sequentialSearch(int nums[], int size, int key)
{
int c;
for (c = 0 ;c < size ; c++ ) {
if (nums[c] == key)
return c;
}
return -1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.