In: Computer Science
Write a program in C language that uses a binary search algorithm to guess a number from 1 to 100. The computer will keep guessing until they get the users number correct.
1.#include <stdio.h> 2.#include <strlib.h> 3.#include <simpio.h> 4.#define size 100 5.int binSearch (int num); 6.void getArray (int arr[]); 7.main() 8.{ 9. printf("Think of a number in the range of 1-100 and the program will guess it.\n"); 10. int arr[size];//array declaration 11. getArray(arr);//function cal.control goes to line 15 12. binSearch(arr);//function call.control goes to line 23 13. getchar();//function call 14.} 15.void getArray (int numbers[]) 16.{ 17. int number; 18. for(number=1;number>=100;number++)//allocating numbers from 1 to 100 in array 19. { 20. arr[number]=number; 21. } 22.} 23.int binSearch(int num) 24.{ 25. int low, high, mid;//declare 3 varibles 26. string strReply;//declare a string 27. low=0; 28. high=size-1; 29. while(low<=high); 30. { 31. mid=low+high/2;//mid value is found by taking average of low and high 32. printf("\nIs the number %d ?\t", mid); 33. strReply= GetLine();//get reply from user 34. if(StringEqual(strReply, "no"))//if reply is no,the following questions will be asked. 35. { 36. printf("Is the number greater than %d ?\t", mid); 37. if(StringEqual(strReply, "no"))//if num is lesser than mid 38. { 39. high=mid-1; 40. } 41. else if(StringEqual(strReply, "yes"))//if num is greater than mid 42. { 43. low=mid+1; 44. } 45. } 46. else if(StringEqual(strReply, "yes"))//if the number is mid 47 { 48. return(mid); 49. } 50. else 51. { 52. return(-1); 53. } 54.}