Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple number guessing game using binary search algorithm in C

This program requires me to: Write a program that plays a simple number-guessing with its user. The user thinks of a number and then answers a series of questions asked by the computer until it correctly guesses the number.

My problem is that the compiler says that: 'arr' undeclared (first use in this function)

Here is my code so far:

#include <stdio.h>
#include "strlib.h"
#include "simpio.h"

#define size 200

int binSearch (int num);
void getArray (int arr[]);

main()
{
      printf("Think of a number in the range of 1-200 and I'll guess it.\n");
      int arr[size];
      getArray(arr);
      binSearch(arr);
      getchar();
}

void getArray (int numbers[])
{
      int number;

      for(number=1;number>=200;number++)
      {
                 arr[number]=number;                                 
      }    
}

int binSearch(int num)
{
      int low, high, mid;
      string strReply;

      low=0;
      high=size-1;

      while(low<=high);
      {
                 mid=low+high/2;
                 printf("\nIs the number %d ?\t", mid);
                 strReply= GetLine();
                 if(StringEqual(strReply, "no"))
                 {
                          printf("Is the number less than %d ?\t", mid);
                          if(StringEqual(strReply, "no"))
                          { 
                                     high=mid-1;                         
                          }
                          else if(StringEqual(strReply, "yes"))
                          {
                                     low=mid+1;     
                          }
                 }
                 else if(StringEqual(strReply, "yes"))
                 { 
                          return(mid);     
                 }
                 else
                 {
                          return(-1);    
                 } 
}

Thank you :)

like image 653
C_Intermediate_Learner Avatar asked Jun 14 '26 10:06

C_Intermediate_Learner


1 Answers

void getArray (int numbers[])
{
  int number;

  for(number=1;number>=200;number++)
  {
             arr[number]=number;     // this should be numbers[number]                            
  }    
}

You pass the array to the function, but use the array as if it were global.

like image 186
Adrian Jandl Avatar answered Jun 16 '26 06:06

Adrian Jandl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!