Need help with menu driven search and sort program

In summary, the user is supposed to be able to choose from a menu of options. The options are: 1) Fill the array with random numbers. 2) Print the array. 3) Search the array. 4) Sort the array. 5) Quit.
  • #1
leroyjenkens
616
49
Hello, this is sort of a big program and I wrote out the program, but I'm unsure about a lot of things.

The program is supposed to give the user a menu of choices:
1) Fill the array with random numbers.
2) Print the array.
3) Search the array.
4) Sort the array.
5) Quit.

Option one is supposed to fill an array with 50 random numbers. Option 2 prints the array. Option 3 searches the array. But it needs to use two different search methods depending on if the array is sorted or not. If it's not sorted, I'm supposed to use sequential searching, if it's sorted, then I'm supposed to use binary searching. Then 4 sorts the array. I chose bubble sorting arbitrarily.

I'm not sure how to make the program do one search method over another, so I just made two different functions for the two different search methods. How do I make it do the sequential search if it's unsorted and the binary search if it's sorted?


Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int getOption (void)
{
    int option;

    printf("Fill Array With Random Numbers\n1- Print the Array\n2- Search the Array\n3- Sort the Array\n4- Quit\n\n");
    scanf("%d", &option);

        if (option<=0 || option>4)
    printf("\nError: That number is not an option.\n");

        if (option=4)
    printf("Bye");

  return option;
}
int fillArray (int option)
{
    int range;
    int getOption (void);
    srand(time(NULL));
    range = (999 - 0) + 1;
}
int printArray (int range)
{

    printf("%d", rand() % range);

}
bool seqSearch (int list[], int last, int target, int* location)
{
    int looker;
    bool found;

    looker = 0;
    while (looker < last && target != list[looker])
        looker++;

    *location = looker;
    found = (target == list[looker]);
    return found;

}
bool binarySearch (int list[], int end, int target, int* location)
{
    int first;
    int mid;
    int last;
    
    first = 0;
    last = end;
    while (first <= last)
        {
            mid = (first + last) / 2;
            if (target > list[mid])
                first = mid + 1;
            else if (target < list[mid])
                last = mid - 1;
            else
                first = last + 1;
        }
    *location = mid;
    return target == list[mid];
}
void sortArray (int list[], int last)
{   
    int temp;
    
    for(int current = 0; current < last; current++)
        {
            for (int walker = last; walker > current; walker--)
                if (list[walker] < list[walker - 1])
                    temp = list[walker];
                    list[walker] = list[walker - 1];
                    list[walker - 1] = temp;
        }
}


Thanks.
 
Technology news on Phys.org
  • #2
You need a variable to keep track of whether or not the list has been sorted or not. When you choose 'fill the array with random numbers' the flag will be false and when you choose 'sort the array' it will be true.
 
  • #3
DavidSnider said:
You need a variable to keep track of whether or not the list has been sorted or not. When you choose 'fill the array with random numbers' the flag will be false and when you choose 'sort the array' it will be true.

Thanks for the response. How would I do that? Would I use an "if" statement? And which function would I put it in?
 
  • #4
Do you have a main() function? This is where you will define the flow of your program, but I don't see it.
 
  • #5
Adyssa said:
Do you have a main() function? This is where you will define the flow of your program, but I don't see it.

I didn't make it yet because I wasn't sure what to put in it. Is that where I put all the function names that I'm going to use throughout the program? I'm not really clear on what main is for. I used to just make a main function and put everything in it. Now that I'm required to make more than one function, I'm not really sure what main is for.

Thanks for the response.
 
  • #6
"main" is where you program starts execiting. Different programming languages and operating systems have different conventions to say where your program starts, but in C (at least for the sort of programs you are currently writing) you must always write a function called "main". Often the "main" function doesn't do much itself, except declare any variables that will be used "everywhere" in the program, and call other functions to do the "real work".

To start this off the same way as my other answer:
Code:
int main()
{
    int sorted;
    int option;

    loop for ever
    {
        prompt_for_a_menu_item();
        read_a_menu_item();
        if (option == 1)
            Fill_the_array_with_random_numbers();
            sorted = false;
        if (option == 2}
            Print_the_array();
        if (option == 3)
            if (sorted = true) Search_the_sorted_array();
            else Search_the_unsorted_array();
        if (option == 4)
            Sort_the_array();
            sorted = true;
        if (option == 5)
            Quit();
    }
}

Writing programs is easy, if the programming language has all the "magic commands" you need to do what your program needs to do (like the above example).

But you can make up your own "magic commands" - they are called "functions"...

Actually, there's something missing from my example. The user can (presumably) pick optiosn from the menu in any order, but it doesn't make any sense do options 2 3 or 4 before doing option 1. So you really need another "true or false" variable to say if the data has been read in, and test it before you try to do the other operations.
 
Last edited:
  • #7
When I write a program like this, I always start with main(), similar to what AlephZero wrote. I write "stubs" (short versions) for all the functions that don't do anything except display a message like "Sorry, I don't know how to sort yet." At this point I have something that should compile and run. I can exercise the menu, even though it doesn't really do anything.

Then I would write the function that fills the array with random numbers, and the function that prints (displays) the array. I can test them simply by choosing the appropriate menu items.

Then I would write a sort function and use the already-working parts of the program to test it. Then include the logic to sort only if the array isn't sorted already, etc.
 
  • #8
Ok I did the first two options, but I can't get the search option to work. I tried implementing it into the program, but it doesn't work. Is there a simpler way to search than what I wrote in the code in my first post? Because that's a lot of text and it just ends up giving me lots of errors.

Here's what I have so far:

Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int sorted;
    int option;
    int range;
    int getOption (void);

    do
    {printf("1- Fill Array With Random Numbers\n2- Print the Array\n3- Search the Array\n4- Sort the Array\n5- Quit\n\n");
    scanf("%d", &option);

    if (option<=0 || option>5)
        printf("\nError: That number is not an option.\n");

    if (option==1)
        {
        srand(time(NULL));
        range = (999 - 0) + 1;
        }
    if (option==2)
        printf("%d\n", rand() % range);
    }
    while(option!=5);
}

Thanks for the replies.
 
  • #9
I assume you're talking about doing a sequential search. We can see the code for your search function, but you don't show the code in main where you are calling this function. Your seqSearch function returns a Boolean value that indicates whether it found the requested item in the array. If the item was found, when seqSearch returns, the index of the item's position in the array is also made available, so your main function needs to have logic to use this information. Show us that code and the list of errors you're getting, and I'm sure we can figure it out.

jtbell makes some good points in post #7. Based on what I see here and what I saw in your thread on the calendar program, you are trying to write the program from the bottom up, rather than from the top down. By not writing the main function first you are creating the building blocks of your programs without having a clear idea of how the blocks need to go together.
 
  • #10
Mark44 said:
I assume you're talking about doing a sequential search. We can see the code for your search function, but you don't show the code in main where you are calling this function. Your seqSearch function returns a Boolean value that indicates whether it found the requested item in the array. If the item was found, when seqSearch returns, the index of the item's position in the array is also made available, so your main function needs to have logic to use this information. Show us that code and the list of errors you're getting, and I'm sure we can figure it out.

jtbell makes some good points in post #7. Based on what I see here and what I saw in your thread on the calendar program, you are trying to write the program from the bottom up, rather than from the top down. By not writing the main function first you are creating the building blocks of your programs without having a clear idea of how the blocks need to go together.

Yes, I'm trying to do a seqSearch first, since the array will be unsorted at first.

Here's the error I get.
error: expected '=', ',', ';', 'asm' or '__attribute__' before 'seqSearch'

And here's the code. I took the sequential search code from the book.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
bool seqSearch (int list[], int last, int target, int* location);
int main()
{
    int sorted;
    int option;
    int range;
    int getOption (void);

    do
    {printf("1- Fill Array With Random Numbers\n2- Print the Array\n3- Search the Array\n4- Sort the Array\n5- Quit\n\n");
    scanf("%d", &option);

    if (option<=0 || option>5)
        printf("\nError: That number is not an option.\n");

    if (option==1)
        {
        srand(time(NULL));
        range = (999 - 0) + 1;
        }

    if (option==2)
        printf("%d\n", rand() % range);

    if (option==3)
        {
            int looker;
            bool found;

            looker = 0;
            while (looker < last && target != list[looker])
                looker++;

            *location = looker;
            found = (target == list[looker]);
            return found;

        }

    }
    while(option!=5);
}

By not writing the main function first you are creating the building blocks of your programs without having a clear idea of how the blocks need to go together.
I just figured I'd put everything in one function right now and then separate it into separate functions later. I don't really need functions for it to work, right? The assignment demands that I do use separate functions, so I'll have to separate them after I find out if it works.
 
  • #11
You have changed the structure of your program, so I believe the compiler or linker is now confused.

In post #1 you had a bunch of function definitions, but no main. In the latest iteration, you have main but no function definitions. (There is the prototype for seqSearch, but no definition for it.) You have taken the code out of seqSearch and stuck it in main.

You have also gotten rid of your other functions, and seem to be writing the code inline in main.

main should be short and sweet. Aside from the declarations of things it needs to pass to the function, the only logic present in main should be a loop. In the loop you call getOption and then decide from the value returned by getOption which function to call (fillArray, printArray, seqSearch, binSearch).

As already mentioned, you'll need a variable in main to keep track of whether the array is sorted. You'll also need a variable to keep track of whether the array has been created. You don't want to print or sort the array if it hasn't been filled yet.

Start thinking about main as being a manager who delegates tasks to the people would report to him or her. The manager (main) has to keep track of the overall project, but leaves the details of the tasks that make up the project to the workers (functions).

The manager usually has to provide some information to the workers so that they can complete their assigned task, and when they are finished, the report some information back to the manager. In your program, when main calls a function, it passes some information in the argument list of the function, and uses the value returned by the function.

Code:
int main(int argc, char** argv)
{
  // pseudocode
  while input choice != 5
  {
      getOption


}
 
  • #12
main should be short and sweet. Aside from the declarations of things it needs to pass to the function, the only logic present in main should be a loop. In the loop you call getOption and then decide from the value returned by getOption which function to call (fillArray, printArray, seqSearch, binSearch).
So should I get rid of the "do while" loop and separate each option into separate functions? And then put getOption in a loop with the printf that prints the menu?
So far I have this in main...
Code:
{
    do
    {
        printf("1- Fill Array With Random Numbers\n2- Print the Array\n3- Search the Array\n4- Sort the Array\n5- Quit\n\n");
        scanf("%d", &option);
        getOption
    }
    while()
}

How do I use getOption to pick which function I want to choose?
And what do I put in the argument of "while()"?
As already mentioned, you'll need a variable in main to keep track of whether the array is sorted. You'll also need a variable to keep track of whether the array has been created. You don't want to print or sort the array if it hasn't been filled yet.
Do I use bool to keep track of whether it has been sorted? Because I can never get bool to work.
Start thinking about main as being a manager who delegates tasks to the people would report to him or her. The manager (main) has to keep track of the overall project, but leaves the details of the tasks that make up the project to the workers (functions).
I'm slowly starting to understand. Slowly.
The manager usually has to provide some information to the workers so that they can complete their assigned task, and when they are finished, the report some information back to the manager. In your program, when main calls a function, it passes some information in the argument list of the function, and uses the value returned by the function.
Ok so the function will be like this...

int function (something here)

The "something here" is the information the main passes to the function? And then the main gets back some information from the function?
 
  • #13
leroyjenkens said:
So should I get rid of the "do while" loop and separate each option into separate functions?
No, don't get rid of the loop. You want to keep asking the user to select an option. When the user enters 5, that's the option to quit.
leroyjenkens said:
And then put getOption in a loop with the printf that prints the menu?
Yes, but there will need to be some other logic in the loop. For starters, the user is allowed to enter 1, 2, 3, 4, or 5 and that's all. If the user enters one of these values, call a function to perform what the user is asking for.

leroyjenkens said:
So far I have this in main...
Code:
{
    do
    {
        printf("1- Fill Array With Random Numbers\n2- Print the Array\n3- Search the Array\n4- Sort the Array\n5- Quit\n\n");
        scanf("%d", &option);
        getOption
    }
    while()
}
As pseudocode, it's a start.
leroyjenkens said:
How do I use getOption to pick which function I want to choose?
You don't. The only thing getOption needs to do is print the menu and return the choice. In your code in post #1 you have it looking for 0, 1, 2, 3, or 4. I would have it look for 1, 2, 3, 4, or 5. If the user chose one of these numbers, return that number. If the user chooses a number outside that range, I would have the function return 0.

In main the code would look something like this:
Code:
.
.
.
result = getOption();
if (result == 0)
{
   // User entered a bad value, so run loop again.
}
else
{
  // Call appropriate function to fill array, print array, etc.
}
leroyjenkens said:
And what do I put in the argument of "while()"?
How about while (option != 5)
leroyjenkens said:
Do I use bool to keep track of whether it has been sorted? Because I can never get bool to work.
I don't know what C implementation you're using. bool was not part of earlier C offerings, so what people did was to set boolean type variables to either 1 (for true) or 0 (for false). If your compiler recognizes true and false, then you can set boolean variables to these values, and test them with if statements.
Code:
if (expr == true) <do something>;
else <do something else);
leroyjenkens said:
I'm slowly starting to understand. Slowly.
Good!
leroyjenkens said:
Ok so the function will be like this...

int function (something here)

The "something here" is the information the main passes to the function? And then the main gets back some information from the function?
I don't know why you're asking this. In post #1 you have definitions of the functions you need. Some of them still need work. For example, you have fillArray and sortArray as functions that return an int value, but in the definitions you don't actually return anything. If they don't return a value, make them void functions.

Void functions cause something to happen.
Nonvoid functions evaluate to something.
They are called in different ways.
Code:
voidFunc();
result = intFunc();
A function that returns a value can have its return value stored in a variable (as above) or be a part of an expression, such as
printf("Return value is ", intFunc());
or as option + intFunc()

Hope that helps...
 
  • #14
Code:
int main (result,option)
{
    result = getOption();
    do
    {
        printf("1- Fill Array With Random Numbers\n2- Print the Array\n3- Search the Array\n4- Sort the Array\n5- Quit\n\n");
        scanf("%d", &option);

        if (option==0 || option>5)
            printf("Invalid Option");

        else if (option==1)
            fillArray(option);

        else if (option==2)
            printArray(range);

        else if (option==3)
            
    }
    while(option!=5);
}

Under the "else if" statements, am I doing that right? I'm trying to get the thing to use the function I created that fills the array.
 
  • #15
More like this:
Code:
[STRIKE]int main (result,option)[/STRIKE]
int main(int argc, char ** argv)
{
   // declarations all variables used in main here
   // following is a mix of C and pseudocode
    do
    {
      result = getOption();
      [STRIKE]if (option==0 || option>5)[/STRIKE]
      // Have getOption return 0 for any bad input (too big or too little)
      // and otherwise return 1, 2, 3, 4, or 5
      if (result == 0) 
      {
         printf("Invalid option");
         continue;
      }

      else if (result==1)
         fillArray(option);
         // Why are you passing option to fillArray? 
         // Think about the information that fillArray needs to create an array,
         // like a parameter for the array and another one for its size.
         // After the array is filled set an isFilled boolean variable to true.
         // The initial value of isFilled should be false.

      // Here you need more logic. The program should not print the array if
      // it isn't filled. The condition to print the array is result == 2 AND isFilled == true.
      // Also, what information does a function that needs to print an array need?
      else if (result==2)
         printArray(range);

      // As before, you shouldn't be able to search an array if it hasn't been filled.
      // Also, you have two kinds of seach capability - sequential or binary.
      // If the array has already been sorted use the binary search.
      // If the array has not been sorted, use the sequential search.
      // Keep track of the array status with another boolean variable, isSorted.
      // At the start, isSorted should be set to false. When the array has been
      // sorted, set this variable to true.
      // In summary when result == 3, you need to check two other 
      // things: isFilled and isSorted.
      // Note that both of your seach functions return a value, so
      // plan to do something with that value.
      else if (result==3)
         search the array

      // Check first to see if the array has been filled.
      // After the array is sorted, set the boolean variable isSorted to true.
      else if (result == 4)
         sort the array

      else if (result == 5)
         print goodbye message
    }
    while(option!=5);
   return 0;
}

Looking back at the code you posted in post #1, there are some problems with it, particularly with fillArray and printArray, neither of which actually has an array type parameter, nor does anything with an array. These two functions will require more work.
 
  • #16
I can't find anything in my book or online on how to use "getOption". That one is new to me. Is there an alternate way?
We've also never done anything with the "int argc, char ** argv" before. This is the first I've seen that.

Does this look good so far?
Code:
int option, array;
    bool isFilled;
    bool isSorted = false;
    do
    {
        isFilled = false;
        result = getOption();
        printf("1- Fill Array With Random Numbers\n2- Print the Array\n3- Search the Array\n4- Sort the Array\n5- Quit\n\n");
        scanf("%d", &option);

        if (result == 0)
      {
         printf("Invalid option");
         continue;
      }

        else if (result==1)
         {fillArray(0-999, 50);
            isFilled = true;
         }

        else if (result==2 && isFilled = true)
            for(int i=0;i<5;, i++);
                printf("%d", array[i])

        else if (result==3 && isSorted = true)
            {
                seqSearch();
                else
                    binarySearch();
            }
        else if (result==4 && isFilled = true)
                sortArray();

        else if (result==5)
                printf("Goodbye");
}
    while(option!=5);
}

Thanks
 
  • #17
leroyjenkens said:
I can't find anything in my book or online on how to use "getOption". That one is new to me. Is there an alternate way?
You write getOption.
leroyjenkens said:
We've also never done anything with the "int argc, char ** argv" before. This is the first I've seen that.
That's a pretty standard way of writing the arguments to main. If you haven't seen it before, you can omit them.
Code:
int main()
{
   ...
}

BTW, your code below is supposed to be the main function but you have omitted the header for it.
leroyjenkens said:
Does this look good so far?
There are a lot of mistakes. I'll summarize them at the end of my post.
leroyjenkens said:
Code:
int option, array;
    bool isFilled;
    bool isSorted = false;



    do
    {
        isFilled = false;
        result = getOption();
        printf("1- Fill Array With Random Numbers\n2- Print the Array\n3- Search the Array\n4- Sort the Array\n5- Quit\n\n");
        scanf("%d", &option);

        if (result == 0)
      {
         printf("Invalid option");
         continue;
      }

        else if (result==1)
         {fillArray(0-999, 50);
            isFilled = true;
         }

        else if (result==2 && isFilled = true)
            for(int i=0;i<5;, i++);
                printf("%d", array[i])

        else if (result==3 && isSorted = true)
            {
                seqSearch();
                else
                    binarySearch();
            }
        else if (result==4 && isFilled = true)
                sortArray();

        else if (result==5)
                printf("Goodbye");
}
    while(option!=5);
}

Thanks
Major errors
1. Your calls to seqSearch, binSearch, and sortArray have no arguments. In your first post you show definitions for these functions, all of which have parameters. You will not be able to get this program to compile (let alone run) until you have a clear understanding of how to pass arguments to a function.
2. You are calling seqSearch and binarySearch as if they were void functions. They are not, based on the definitions for them that you showed in post #1. I'm guessing that these functions were given during class, because they look like they were written by someone who understands argument passing. I'm also guessing that you wrote the definitions for fillArray and printArray - they are pretty much useless as they are currently written, since they do not have the right parameters and they don't do anything with an array, despite their names. These functions need to be completely rewritten.
The functions don't need to be fully implemented, but they need to be callable from main, which means that the argument list needs to be fleshed out so that main knows what information to pass to the function body.
3. main needs to define the array that will be used by several of the functions it calls. You have a variable named array, but it is a scalar variable (capable of holding one value) not an array.
4. Inside your loop you call getOption() and then print the menu. The whole reason for getOption is to print the menu and return the user's choice. The loop should not be displaying the menu options.
5. Your call to fillArray looks like this --
fillArray(0-999, 50);
I believe you think you are passing a range of values, but 0 - 999 is a subtraction expression that evaluates to -999. As already noted, fillArray needs to be completely rewritten. To start you need to determine what information needs to be passed to this function in the argument list.
6. For option 2 (print the array), you have this code:
for(int i=0;i<5;, i++);
printf("%d", array)
You should be calling printArray to print the array, not doing it directly in main.
Also, the loop here runs 5 times. Why do you think there are 5 values in the array?
7. This logic is incorrect -
seqSearch();
else
binarySearch();
You have an else without a preceding if.

Other errors
1. Initialize isFilled to false at the top of main, not inside your loop. Doing so in the loop causes it to be reset each iteration of the loop.
2. After you call sortArray, set isSorted to true. That's the variable you need to use to determine which of your sort functions to call.
If the array has not been sorted, call seqSearch.
If the array has been sorted, call binarySearch.

There might be more problems, but these will give you something to do.
 
  • #18
You write getOption.
My problem is I can never tell in coding examples whether a phrase like "getOption" specifically does something, or if it's just a variable worded like that for my sake, so I know where it goes in the program.

Another reason I asked was because I looked it up and it kept bringing up "getOpt", and I wasn't sure if that was the same thing.
There are a lot of mistakes. I'll summarize them at the end of my post.
I know, I just posted it like that to see if I'm headed in the right direction.

Here's the whole thing of what I've changed. I'll list what I don't understand at the bottom.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
    int result;
    int option;
    int array[50];
    bool isFilled = false;
    bool isSorted = false;

        isFilled = false;
        result = getOption();
        printf("1- Fill Array With Random Numbers\n2- Print the Array\n3- Search the Array\n4- Sort the Array\n5- Quit\n\n");
        scanf("%d", &option);    do
    {

        if (result == 0)
            {
            printf("Invalid option");
            continue;
            }
        else if (result==1)
         fillArray();
         

        else if (result==2 && isFilled = true)
            printArray(array[i]);

        else if (result==3 && isSorted = true)
            {
                if
                    seqSearch(list[50],last,target,*location);
                else
                    binarySearch(list[50],end,target,*location);
            }
        else if (result==4 && isFilled = true)
                {sortArray(list[50],last);
                isSorted = true;
                }

        else if (result==5)
                printf("Goodbye");
    }
    while(option!=5);
    return result;
}
int getOption (void)
{
    
}
int fillArray (int option)
{
    int range;
    int getOption (void);
    srand(time(NULL));
    range = (999 - 0) + 1;
}
int printArray (int range)
{

    for(int i=0; i<50; i++);
    printf("%d", array[i]);

}
int seqSearch (int list[], int last, int target, int* location)
{
    int looker;
    int found;

    looker = 0;
    while (looker < last && target != list[looker])
        looker++;

    *location = looker;
    found = (target == list[looker]);
    return found;

}
int binarySearch (int list[], int end, int target, int* location)
{
    int first;
    int mid;
    int last;

    first = 0;
    last = end;
    while (first <= last)
        {
            mid = (first + last) / 2;
            if (target > list[mid])
                first = mid + 1;
            else if (target < list[mid])
                last = mid - 1;
            else
                first = last + 1;
        }
    *location = mid;
    return target == list[mid];
}
void sortArray (int list[], int last)
{
    int temp;
    int walker;
    for(int current = 0; current < last; current++)
        {
            for (int walker = last; walker > current; walker--)
                if (list[walker] < list[walker - 1])
                    temp = list[walker];
                    list[walker] = list[walker - 1];
                    list[walker - 1] = temp;
        }
}

This thing never let's me use "bool". I can use "int" and "char" and "float" just fine, but the moment I try to use "bool" it gives me an error saying it's undeclared.

I'm still not sure exactly what I do with getOption. Like I said above, I'm not sure if it's like printf and scanf and it does its own thing that the program sees and knows it does a specific thing. But some things like "isFilled" from my program don't do anything that has to do with the name. The program doesn't recognize the words "is filled" and then knows that it has to do with filling an array. The name is only the way it is so that I recognize what it's there for. You know what I mean? This is one of the things about programming that might be keeping my brain from understanding it. Because right now my brain is refusing to understand this.

Well I changed everything, I think. It's only giving me errors about undefined things, like "bool" and "i" and all this other stuff.

Thanks.
 
  • #19
leroyjenkens said:
Well I changed everything, I think. It's only giving me errors about undefined things, like "bool" and "i" and all this other stuff.
"bool" is not a native C type. You could just use "int" instead, or you could typedef "bool" to "int". You didn't delcare "i" in the functions where you use it.
 
  • #20
You're making some progress... What you have is much better than the previous version.

Comments
1.
bool isFilled = false;
bool isSorted = false;

Change these to int isFilled = 0; and similar for the other one.
Also, remove the line just below that says isFilled = false;
That's redundant.
2. In this code,
...result = getOption();
...printf("1- Fill Array With Random Numbers\n2- Print the Array\n3- Search the Array\n4- Sort the Array\n5- Quit\n\n");
...scanf("%d", &option);
The call to getOption should be inside the loop.
The printf and scanf statements should be inside the getOption function.
A question that you've asked before and I answered before still has you puzzled. getOption is not a standard library function like printf and scanf - it is a function that you write. printf and scanf and a bunch of others are already written for you. Your program can access them by including the header that has their prototypes, stdio.h.

3. The first few lines in your loop should look like this:
Code:
    do
    {
        result = getOption();
        if (result == 0)
        {
            printf("Invalid option");
            continue;
        }
        else if (result==1)
        // and so forth
4. You have this in the next else clause:
Code:
       else if (result==1)
         fillArray();
As already noted, fillArray needs to be rewritten. At minimum main needs to pass the array as a parameter, and should also pass the size of the array. Any other information needed by fillArray (such as the range of values) should also be passed.

Also, after you call fillArray(...), set isFilled to 1, signifying that the array has been initialized.
5. The next else clause should have this logic:
Code:
       else if (result==3)
       {
          if the array hasn't been filled, print an error message and continue
          otherwise, if the array hasn't been sorted, call seqSearch
          otherwise, call binarySearch
       }
Note that this logic is different from what I suggested before.
6. Here's the logic you need for the next else clause
Code:
      else if (result==4)
      {
          if the array hasn't been filled, print an error message and continue
          otherwise, call sortArray and then set isSorted to 1.
      }
Note that this logic is also different from what I advised earlier.

7. fillArray
This is what you currently have:
Code:
int fillArray (int option)
{
    int range;
    int getOption (void);
    srand(time(NULL));
    range = (999 - 0) + 1;
}
a. Passing option to this function makes no sense.
b. getOption should not be called in this function.
c. "range" is really two numbers - a minimum value and a maximum value. Both should be parameters whose values get passed in a call to this function.
d. The parameters to this function should be - the array, the size of the array, the min value of each element of the array, the maximum value of each element of the array.
e. The last line of your code sets range to 1000 - not what you want.
As a start for this function, just have it fill an array with every number the same. Work on the details of getting random values after you are able to call the function from main.

8. printArray
Here's your code:
Code:
int printArray (int range)
{

    for(int i=0; i<50; i++);
    printf("%d", array[i]);

}
a. The range parameter makes no sense. The information that this function needs is the array itself and the size of the array. Nothing else.
b. You have the function returning an int, but you don't actually return anything. This function seems an ideal candidate for being a void function.
 
  • #21
leroyjenkins said:
I'm still not sure exactly what I do with getOption. Like I said above, I'm not sure if it's like printf and scanf and it does its own thing that the program sees and knows it does a specific thing. But some things like "isFilled" from my program don't do anything that has to do with the name. The program doesn't recognize the words "is filled" and then knows that it has to do with filling an array. The name is only the way it is so that I recognize what it's there for. You know what I mean? This is one of the things about programming that might be keeping my brain from understanding it. Because right now my brain is refusing to understand this.
I already gave you some advice for getOption.

As far as isFilled and isSorted, these are variables that main stores values in so that it can keep track of the state of the array.

At the start, the array is uninitalized (and therefore, unsorted), so isFilled and isSorted are set to 0 (signifying false). After fillArray is called, isFilled gets set to 1 (signifying true). After sortArray is called, isSorted gets set to 1 so that the appropriate search function can be called.
 
  • #22
How about something a little more like this?
Code:
#include <stdbool.h>

int main()
{
    bool sorted;
    bool option;

     while (option != 5)
    {
        prompt_for_a_menu_item();
        read_a_menu_item();
        switch (option)
        {
           case 1:
               Fill_the_array_with_random_numbers();
               sorted = false;
               break;

           case 2:
              print_array();
              break;

           case 3:
              if (sorted = true) Search_the_sorted_array();
              else Search_the_unsorted_array();
              break;

          case 4:
             Sort_the_array();
             sorted = true;
             break;

          default:
             printf("%c is an invalid choice.\n");
    }
}
 
  • #23
Bill, there are a few problems with your code.
option should not be type bool.
What happens if a user chooses options 2, 3, or 4 before the array is filled?
If a user chooses option 3, Search_the_sorted_array() always gets called.
 
  • #24
Ok I tried using the cases and made a mess, but which one is closer to a working program, this one or my old one?

Code:
#include <stdbool.h>
#include <stdio.h>
int fillArray (int ary[], int range, int getOption);
void printArray ();
int binarySearch (int list[], int end, int target, int *location);
int seqSearch (int list[], int last, int target, int *location);
void sortArray (int list[], int last);
int main()
{
    bool sorted;
    bool option;
    int getOption;
    int range;
    int i;
    int ary[50];
    int list[50];
    int last;
    int target;
    int location;
    int end;

     while (option != 5)
    {
        printf("1- Fill Array\n2- Print Array\n3- Search Array\n4- Sort Array");
        scanf("%l", &option);
        switch (option)
        {
           case 1:
               fillArray(int ary[], int range, int getOption);
               sorted = false;
               break;

           case 2:
              printArray();
              break;

           case 3:
              if (sorted = true) binarySearch(list[50], end, target, *location);
              else seqSearch(list[50], last, target, *location);
              break;

          case 4:
             sortArray(list[50], last);
             sorted = true;
             break;

          default:
             printf("%c is an invalid choice.\n");
    }
    return 0;
}
int fillArray (int ary[], int range)
{
    int range;
    srand(time(NULL));
    range = (999 - 0);

}
void printArray ()
{
    for(i=0; i<50; i++);
    printf("%d", ary[i]);

    return 0;
}
int binarySearch (int list[], int end, int target, int* location)
{
    int first;
    int mid;
    int last;

    first = 0;
    last = end;
    while (first <= last)
        {
            mid = (first + last) / 2;
            if (target > list[mid])
                first = mid + 1;
            else if (target < list[mid])
                last = mid - 1;
            else
                first = last + 1;
        }
    *location = mid;
    return target == list[mid];
}
int seqSearch (int list[], int last, int target, int* location)
{
    int looker;
    int found;

    looker = 0;
    while (looker < last && target != list[looker])
        looker++;

    *location = looker;
    found = (target == list[looker]);
    return found;

}
void sortArray (int list[], int last)
{
    int temp;
    int walker;
    for(int current = 0; current < last; current++)
        {
            for (int walker = last; walker > current; walker--)
                if (list[walker] < list[walker - 1])
                    temp = list[walker];
                    list[walker] = list[walker - 1];
                    list[walker - 1] = temp;
        }
    return 0;
}

I'm getting some errors that I don't know what to do with.
Like "too few arguments to function fillArray"
"Expected expression before int" at the case 3 "if" statement line.
"too few arguments to function 'binarySearch'"
"invalid type argument of 'unary *' (have 'int')" at the case 3 "else" statement line.
in my fillArray function it says range is redeclared as a different kind of symbol.
I tried to fix these and can't figure out how.
 
  • #25
Please go back and carefully reread posts 17, 20, and 21. I spent a lot of time writing them, and you are ignoring (or not understanding) some of what I wrote. I don't want to have to write it again.
If there is something I said before that you don't understand - ask.
leroyjenkens said:
I'm getting some errors that I don't know what to do with.
Like "too few arguments to function fillArray"
"Expected expression before int" at the case 3 "if" statement line.
"too few arguments to function 'binarySearch'"
"invalid type argument of 'unary *' (have 'int')" at the case 3 "else" statement line.
in my fillArray function it says range is redeclared as a different kind of symbol.
When you call fillArray in case 1, you have
fillArray(int ary[], int range, int getOption);
You should NOT have the types in the parameter list.
Also, why is getOption listed here? Your program has already set the value of option.
getOption should have been a function, not a variable, and it definitely should not be a parameter to fillArray.

The error about "expected argument before int" is probably unrelated to case 3. I suspect it is a result of how you are calling fillArray.

"too few arguments to function 'binarySearch' " - There is not a problem with the number of arguments. The prototype, definition, and call to this function all have four arguments. There is a problem with the call, though. When you pass an array to a function, you pass just the name of the array - no brackets. The name of an array is a kind of pointer. It evaluates to the location of the first item in the array.

Be advised that the code shown by Bill McEnaney has an error that is frequently made by C newbies.
 
  • #26
Mark44 said:
Bill, there are a few problems with your code.
option should not be type bool.
What happens if a user chooses options 2, 3, or 4 before the array is filled?
If a user chooses option 3, Search_the_sorted_array() always gets called.
You're right, Mark44, and I can hardly believe that I declared option as a boolean variable. I must have been sleep-coding. ;) Why not fill the array before the loop runs?
 
Last edited:
  • #27
That wasn't the only problem. There's a logical error here:
Code:
  case 3:
              if (sorted = true) Search_the_sorted_array();
              else Search_the_unsorted_array();
              break;
The other problem shows up if the user choosed options 2, 3, or 4 before the array is filled.
 
  • #28
Mark44 said:
That wasn't the only problem. There's a logical error here:
Code:
  case 3:
              if (sorted = true) Search_the_sorted_array();
              else Search_the_unsorted_array();
              break;
The other problem shows up if the user choosed options 2, 3, or 4 before the array is filled.
Did you see the post where I suggested filling the array before the "while" loop. I'd write the function to ensure that the while loop would run only after you filled the array. Oops! That's no good because then you'd need to rerun the program to refill the array.
 
  • #29
Bill,
Did you spot the error here?
Code:
case 3:
              if (sorted = true) Search_the_sorted_array();
              else Search_the_unsorted_array();
              break;

Bill McEnaney said:
Did you see the post where I suggested filling the array before the "while" loop. I'd write the function to ensure that the while loop would run only after you filled the array. Oops! That's no good because then you'd need to rerun the program to refill the array.
I don't think that would be a problem. As I understand things, the array needs to be filled only once.
 
  • #30
Mark44 said:
Bill,
Did you spot the error here?
Code:
case 3:
              if (sorted = true) Search_the_sorted_array();
              else Search_the_unsorted_array();
              break;

I don't think that would be a problem. As I understand things, the array needs to be filled only once.
I see one now, Mark. We need to replace the "=" with "==" or to write:
Code:
case 3:
   if (sorted)
     search_sorted_array();
  else
     search_unsorted_array();
  break;
 
Last edited:
  • #32
Mark44 said:
Yes, exactly.
Oh, good. I can still write C. Pascal is the language I know best.

Why not use the bsearch() and qsort() functions?

I didn't read the code carefully earlier. I just added the switch statement, changed the while condition, and threw in a default clause.
 
  • #33
Please go back and carefully reread posts 17, 20, and 21. I spent a lot of time writing them, and you are ignoring (or not understanding) some of what I wrote. I don't want to have to write it again.
If there is something I said before that you don't understand - ask.
I read everything you write and try to apply it. And I really appreciate you spending the time to help me with this. What did you see that I didn't do that you mentioned previously? I thought I changed them all.
When you call fillArray in case 1, you have
fillArray(int ary[], int range, int getOption);
You should NOT have the types in the parameter list.
Also, why is getOption listed here? Your program has already set the value of option.
getOption should have been a function, not a variable, and it definitely should not be a parameter to fillArray.
I forgot to take it out of case 1. I took it out of the fillArray function, but I left it in case 1 accidentally.
getOption should be a function? So does that mean I put the printf thing that prints the menu in there with the scanf that gets what the user selects?

Here's my code:
Code:
#include <stdbool.h>
#include <stdio.h>
int fillArray (int ary[], int range);
void printArray ();
int binarySearch (int list[], int end, int target, int *location);
int seqSearch (int list[], int last, int target, int *location);
void sortArray (int list[], int last);
int main()
{
    bool sorted;
    int option;
    int getOption;
    int range;
    int i;
    int ary[50];
    int list[50];
    int last;
    int target;
    int location;
    int end;

     while (option != 5)
    {
        printf("1- Fill Array\n2- Print Array\n3- Search Array\n4- Sort Array");
        scanf("%l", &option);
        switch (option)
        {
           case 1:
               fillArray(ary[50], range);
               sorted = false;
               break;

           case 2:
              printArray();
              break;

           case 3:
              if (sorted)
                binarySearch(list[50], end, target, *location);
              else
                seqSearch(list[50], last, target, *location);
              break;

          case 4:
             sortArray(list[50], last);
             sorted = true;
             break;

          default:
             printf("%c is an invalid choice.\n");
    }
    return 0;
}
int fillArray (int ary[], int range)
{
    int range;
    srand(time(NULL));
    range = (999 - 0);

}
void printArray ()
{
    for(i=0; i<50; i++);
    printf("%d", ary[i]);

    return 0;
}
int binarySearch (int list, int end, int target, int* location)
{
    int first;
    int mid;
    int last[50];

    first = 0;
    last = end;
    while (first <= last)
        {
            mid = (first + last) / 2;
            if (target > list[mid])
                first = mid + 1;
            else if (target < list[mid])
                last = mid - 1;
            else
                first = last + 1;
        }
    *location = mid;
    return target == list[mid];
}
int seqSearch (int list[], int last, int target, int* location)
{
    int looker;
    int found;

    looker = 0;
    while (looker < last && target != list[looker])
        looker++;

    *location = looker;
    found = (target == list[looker]);
    return found;

}
void sortArray (int list[], int last)
{
    int temp;
    int walker;
    for(int current = 0; current < last; current++)
        {
            for (int walker = last; walker > current; walker--)
                if (list[walker] < list[walker - 1])
                    temp = list[walker];
                    list[walker] = list[walker - 1];
                    list[walker - 1] = temp;
        }
    return 0;
}

It says "invalid argument type of 'unary *' (have 'int')" on the second line below case 3.
I don't even know what that means.
It says the same thing 2 lines below that.

It says "'range' redeclared as a different kind of symbol."
I don't know why that's a problem, but I don't know how to fix it.

And in the code I got from the book, it has list[mid] in the binary search function. The compiler is saying that's neither an array nor a pointer. What is list[mid] and why is it in the book if it's invalid?
 
  • #34
leroyjenkens said:
It says "invalid argument type of 'unary *' (have 'int')" on the second line below case 3.
I don't even know what that means.

In case 3, you call binarySearch like this:
binarySearch(list[50], end, target, *location);

At the top of main you have this declaration:
int location;

location is an int value, so you cannot dereference it as if it were a pointer.
Also, every one of the variables you declare at the top of main is uninitialized, so when you pass them to your functions, it's GIGO (garbage in, garbage out).

Whenever you pass a value to a function, you need to make sure that you know its value going in. The only exceptions are when the parameter is of some pointer type, which would include array types.

In your while loop, the first thing you test is that option != 5. How do you know that option doesn't have the value 5?

leroyjenkens said:
It says the same thing 2 lines below that.
Same problem in your call to seqSearch as described above.
leroyjenkens said:
It says "'range' redeclared as a different kind of symbol."
I don't know why that's a problem, but I don't know how to fix it.
Here's your code for fillArray.
Code:
int fillArray (int ary[], int range)
{
    int range;
    srand(time(NULL));
    range = (999 - 0);

}
In the parameter list, you're telling the compiler that range is an int. Inside the body of the function, you are redeclaring range. You can't do that.

Also, and as mentioned now three times, this function is broken! You are setting range to 999. One of the many things you've missed that I've said before is that what you're calling the range needs to be two separate variables, a min. value and a max. value.

This function doesn't do anything with an array.
leroyjenkens said:
And in the code I got from the book, it has list[mid] in the binary search function. The compiler is saying that's neither an array nor a pointer. What is list[mid] and why is it in the book if it's invalid?
What difference do you notice between these two lines of code? These are the function headers for your two search routines. One of them is giving you and error and the other is not.
Code:
int binarySearch (int list, int end, int target, int* location)
{
  ...
}

int seqSearch (int list[], int last, int target, int* location)
{
  ...
}
 
  • #35
location is an int value, so you cannot dereference it as if it were a pointer.
Also, every one of the variables you declare at the top of main is uninitialized, so when you pass them to your functions, it's GIGO (garbage in, garbage out).

Whenever you pass a value to a function, you need to make sure that you know its value going in. The only exceptions are when the parameter is of some pointer type, which would include array types.
What do I initialize them as? Like for example, I have int option; I thought the function itself gave them values. Do I need to give them all values?
In your while loop, the first thing you test is that option != 5. How do you know that option doesn't have the value 5?
If it's 5, the program is supposed to quit. 5 would make the loop stop, right? Is that not a good way to do it?
In the parameter list, you're telling the compiler that range is an int. Inside the body of the function, you are redeclaring range. You can't do that.
I took it out of the body. Do I need to put it anywhere else, or is it being declared in the function argument?
Also, and as mentioned now three times, this function is broken! You are setting range to 999. One of the many things you've missed that I've said before is that what you're calling the range needs to be two separate variables, a min. value and a max. value.
Sorry about that, I left that the same because I was trying to find the example in my book that gave me the exact syntax I need and I couldn't find it.
Does it just need to be like int minRange; and int maxRange; or something like that?
What difference do you notice between these two lines of code? These are the function headers for your two search routines. One of them is giving you and error and the other is not.
Ok I changed that and it's accepted now.

I still have it telling me error: invalid operands to binary / (have 'int *' and 'int')
in the binarySearch function, 2 lines under "while". What does that mean?
 

Similar threads

  • Programming and Computer Science
Replies
2
Views
633
  • Programming and Computer Science
Replies
1
Views
944
  • Programming and Computer Science
3
Replies
75
Views
4K
  • Programming and Computer Science
2
Replies
47
Views
4K
  • Programming and Computer Science
Replies
32
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
5
Views
884
  • Engineering and Comp Sci Homework Help
Replies
4
Views
927
  • Programming and Computer Science
Replies
17
Views
2K
  • Programming and Computer Science
Replies
5
Views
3K
Back
Top