Need help with menu driven search and sort program

AI Thread Summary
The discussion centers on creating a menu-driven program in C that allows users to fill an array with random numbers, print the array, search it using different methods based on its sorted status, and sort it. The main challenge is implementing logic to switch between sequential and binary search methods depending on whether the array is sorted, which requires a flag variable to track the sorted state. Participants emphasize the importance of structuring the program with a clear main function that delegates tasks to other functions, rather than trying to combine everything in one place. Suggestions include starting with a simple main function that calls other functions based on user input and ensuring proper function definitions are included. The conversation highlights the need for clarity in program flow and function usage to avoid confusion and errors.
leroyjenkens
Messages
615
Reaction score
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
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.
 
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?
 
Do you have a main() function? This is where you will define the flow of your program, but I don't see it.
 
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.
 
"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:
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.
 
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.
 
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[/color], 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?
 
  • #36
Mark44 said:
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.

leroyjenkins said:
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?
What function? The getOption function was supposed to return a value to the option variable, but you decided not to write this function. Since you don't have a function that sets this variable you need to set it yourself, like, say, to -1.

Mark44 said:
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?

leroyjenkins said:
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?
An uninitialzed variable could have any value in it, including 5. If that happened, your loop wouldn't run at all.

Mark44 said:
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.

leroyjenkins said:
I took it out of the body. Do I need to put it anywhere else, or is it being declared in the function argument?

Mark44 said:
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.

leroyjenkins said:
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?
You need to decide what fillArray should do. Part of that planning is figuring out what inputs it needs (the arguments) and what, if any, the outputs should be. If you want to specify a range of values for the elements of the array, you need to pass in two values.

The header line of a function is a kind of contract between the function and whoever calls it (main in your case).

Mark44 said:
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.

leroyjenkins said:
Ok I changed that and it's accepted now.
How did you change it? It could be that you have now broken both functions.

leroyjenkins said:
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?
It means you are trying to do division with two types that aren't compatible.
Code:
int binarySearch (int list, int end, int target, int* location)
{
    int first;
    int mid;
    int last[50];[/color]
    
    first = 0;
    last = end;
    while (first <= last)
        {
            mid = (first + last) / 2;[/color]
     ...
}
This code was OK before, but you changed it, so now you're getting the error you showed. In a previous iteration, last was an int variable. Now it's an array of ints. Why?

The reason for the error is in the 2nd colored line. first is type int and last is type int * (the name of an array is an address - which makes it a pointer (read-only). The result of adding an int and a pointer to an int is an address - a pointer. The final operation on the right side is to divide the address by 2. Division on pointers is not defined, which is the reason for the compiler error.
 
  • #37
Leroy,
You mentioned before in this or another thread that there are four programming assignments in the class you're taking. I have to say that that doesn't sound like the best way to learn programming. A better approach, I believe, is to write more programs, with each one being focussed on a smaller number of programming concepts.

After you're comfortable with creating algorithms, parameter passing, and pointers, then it's reasonable to combine these ideas in larger programs such as the one you're working on.

The class you're taking sounds like an accelerated programming class. That would probably be OK for someone with some experience in another programming language, but for someone like you with no prior experience, it doesn't add up to a good learning experience.
 
  • #38
What function? The getOption function was supposed to return a value to the option variable, but you decided not to write this function. Since you don't have a function that sets this variable you need to set it yourself, like, say, to -1.
I thought the functions used the value the user inputted.

Do I need the getOption function or will it work the way I have it now?

An uninitialzed variable could have any value in it, including 5. If that happened, your loop wouldn't run at all.
Oh, so that's why I'd set it to -1 so it doesn't get randomly set?
You need to decide what fillArray should do.
fillArray should get random numbers into an array between "1 and 999 inclusive", which is what the assignment states.
I used an example from the book to get the random numbers, and I replaced their (20 - 10), which was random numbers between 20 and 10, with my own range, which is (999 - 1). I assumed just replacing the range of numbers needed would work. I guess not.
Part of that planning is figuring out what inputs it needs (the arguments) and what, if any, the outputs should be. If you want to specify a range of values for the elements of the array, you need to pass in two values.

The header line of a function is a kind of contract between the function and whoever calls it (main in your case).
Like this? range = (1, 999);
How did you change it? It could be that you have now broken both functions.
lol that's a good possibility. I just changed the one that wasn't giving me an error.
So it looks like this now...
Code:
int binarySearch (int list[], int end, int target, int* location)
I guess it could still be wrong.
It means you are trying to do division with two types that aren't compatible.
Oh ok I fixed that.
mid = (first + last[50]) / 2;

This code was OK before, but you changed it, so now you're getting the error you showed. In a previous iteration, last was an int variable. Now it's an array of ints. Why?
Not sure why I changed that. I think it's because I was getting an error from list[mid] and for some reason putting [50] made that error go away. I took it away again and it's not giving me an error. I don't know. It's just list now.
Here's what I have right now...
Code:
#include <stdbool.h>
#include <stdio.h>
int fillArray (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 = -1;
    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(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 range)
{
    srand(time(NULL));
    range = (1, 999);

}
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;
}
It's giving me an error on the very last line at the }. It says "expected declaration or statement at end of input". I've tried putting doing stuff with the return; but nothing is taking that error away.

Edit: Ok I found the problem, I was missing a curly bracket up in the main. So at least there's no errors. My program runs. I wanted to get it running so I could actually see the problems it has. When I hit a number, it begins spamming the screen with the list menu.

Thanks.
 
Last edited:
  • #39
Leroy,
You mentioned before in this or another thread that there are four programming assignments in the class you're taking. I have to say that that doesn't sound like the best way to learn programming. A better approach, I believe, is to write more programs, with each one being focussed on a smaller number of programming concepts.
The semester is over now, and we were given an extra day to turn in this last assignment. This menu one is the only program left in the assignment that I haven't finished. I have to drive up to school to turn in the hard copy before 5 and I have until midnight to email the instructor the actual programs.

I'd never done any programming before this class, so I had no idea how to study. Apparently making programs is the best way to do that, because just reading the book and putting in a few codes from the examples doesn't help me. Now I know. This is just a prereq class for my physics degree, so I'm just trying to get a C. Not sure if I've gotten that C, though. My exam scores were high D's and I did decently on the programs and quizzes. I'm hoping to get this program working so that it'll be enough to get me a C. I really don't want to take this class over again.
After you're comfortable with creating algorithms, parameter passing, and pointers, then it's reasonable to combine these ideas in larger programs such as the one you're working on.

The class you're taking sounds like an accelerated programming class. That would probably be OK for someone with some experience in another programming language, but for someone like you with no prior experience, it doesn't add up to a good learning experience.
It was a 6 week summer class. I was there 4 days a week. I probably would've done a lot better had it been a fall or spring class. Few people in the class did do well, from what I heard in the computer lab, so that made me feel a bit better.
 
  • #40
leroyjenkens said:
I thought the functions used the value the user inputted.
A function can get input from the user (via scanf or other standard library input function) OR it can use the inputs passed in the call to its parameters.
leroyjenkens said:
Do I need the getOption function or will it work the way I have it now?
If the problem statement requires this function, you need it, otherwise not. If it's not required you can get away with what you have.

leroyjenkens said:
Oh, so that's why I'd set it to -1 so it doesn't get randomly set?
Right.
leroyjenkens said:
fillArray should get random numbers into an array between "1 and 999 inclusive", which is what the assignment states.
I used an example from the book to get the random numbers, and I replaced their (20 - 10), which was random numbers between 20 and 10, with my own range, which is (999 - 1). I assumed just replacing the range of numbers needed would work. I guess not.

Like this? range = (1, 999);
I think you're misreading what it says in the book. 20 - 10 isn't two numbers; it's one number, 10. In the same way, 999 - 1 isn't two numbers; it's one number, 998.

You should completely get rid of range as a variable, and instead use two different variables, say minVal and maxVal.

The statement you show above, range = (1, 999); , sets range to 999. To understand why this happens, look up a description of the comma operator in C.
leroyjenkens said:
lol that's a good possibility. I just changed the one that wasn't giving me an error.
So it looks like this now...
Code:
int binarySearch (int list[], int end, int target, int* location)
I guess it could still be wrong.
No, that's fine. Keep in mind that the list parameter is not really an array, despite the "int list[]" notation. It's really the address of an int, so could also be written as "int * list".
leroyjenkens said:
Oh ok I fixed that.
mid = (first + last[50]) / 2;
Actually, this is still broken, for two reasons.
1. According to your code, last is type int, so it makes no sense to use it as if it were an array.
2. Assuming you meant list[50], where list actually is an array, if your array has 50 elements, the indexes run from 0 through 49. list[50] would not be an element of your array.

The correct statement, I believe, is mid = (first + last) / 2;
Here, first and last are type int.
leroyjenkens said:
Not sure why I changed that. I think it's because I was getting an error from list[mid] and for some reason putting [50] made that error go away. I took it away again and it's not giving me an error. I don't know. It's just list now.
Here's what I have right now...
Code:
#include <stdbool.h>
#include <stdio.h>
int fillArray (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 = -1;
    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(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 range)
{
    srand(time(NULL));
    range = (1, 999);

}
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;
}
It's giving me an error on the very last line at the }. It says "expected declaration or statement at end of input". I've tried putting doing stuff with the return; but nothing is taking that error away.

Edit: Ok I found the problem, I was missing a curly bracket up in the main. So at least there's no errors. My program runs. I wanted to get it running so I could actually see the problems it has. When I hit a number, it begins spamming the screen with the list menu.

Thanks.

Looking at the code you show, you should still be getting compiler errors for variables that are undeclared, such as ary in printArray.

There are too many errors in your program for me to list all of them, and I need to leave in a few minutes.
 
  • #41
leroyjenkens said:
The semester is over now, and we were given an extra day to turn in this last assignment. This menu one is the only program left in the assignment that I haven't finished. I have to drive up to school to turn in the hard copy before 5 and I have until midnight to email the instructor the actual programs.

I'd never done any programming before this class, so I had no idea how to study. Apparently making programs is the best way to do that, because just reading the book and putting in a few codes from the examples doesn't help me. Now I know. This is just a prereq class for my physics degree, so I'm just trying to get a C. Not sure if I've gotten that C, though. My exam scores were high D's and I did decently on the programs and quizzes. I'm hoping to get this program working so that it'll be enough to get me a C. I really don't want to take this class over again.
Even if you manage to eke out a grade of C, which doesn't seem likely to me, I would still advise taking this class again. As I mentioned earlier, having a physics degree without any experience in programming would probably limit your options.
leroyjenkens said:
It was a 6 week summer class. I was there 4 days a week. I probably would've done a lot better had it been a fall or spring class. Few people in the class did do well, from what I heard in the computer lab, so that made me feel a bit better.
It shouldn't make you feel all that good, because you're the one who is getting the grade.
 
  • #42
I think you're misreading what it says in the book. 20 - 10 isn't two numbers; it's one number, 10. In the same way, 999 - 1 isn't two numbers; it's one number, 998.

You should completely get rid of range as a variable, and instead use two different variables, say minVal and maxVal.

The statement you show above, range = (1, 999); , sets range to 999. To understand why this happens, look up a description of the comma operator in C.
I took something out of it. Here's the whole thing.
Code:
srand(time(NULL));
    range = (999 - 1) + 1;
    randNo = rand() % range + 1;

So this worked to give me one random number. I need to make it give me 50 random numbers somehow.

I think I'm going to just give up. I have to leave in about an hour to turn this in and this stuff just makes me want to put a gun in my mouth and end it all.
Even if you manage to eke out a grade of C, which doesn't seem likely to me, I would still advise taking this class again. As I mentioned earlier, having a physics degree without any experience in programming would probably limit your options.
I can't express how much I hate this class. I've never hated a subject, so this is a first. If I pass this class, I'll never touch programming again, unless I lose this feeling of hatred I have for it. If that limits my options as a physics person, then so be it. I've got quite a few years before I'd be an actual physicist anyway.
It shouldn't make you feel all that good, because you're the one who is getting the grade.
It makes me feel good because this whole semester I felt like I have a mental handicap for how much I struggle with this. This is the first time I've felt like I'm incapable of learning something. It's not a good feeling. So to find out I'm not the only one makes me feel better, even if I do fail.

I appreciate all the time you spent helping me with this. You probably taught me more about programming in the short time we've talked than I've learned the entire semester. I let the teacher evaluation reflect that with some pretty harsh ratings for that instructor. This class was a joke. Seemed like no one learned anything. Most of them just found a computer science major in the computer lab to basically write the program for them, and everyone else just copied it. Oh well. I have about two years before I get my bachelor's degree, so if I fail, this will be the last class I take. Maybe I won't hate programming with such a passion two years from now.
 
  • #43
Leroy,
I didn't hate the first programming class I had, but I didn't like it very much. The language used in the class was PL/C, a subset of another language (PL/1) that was used a lot back then (early 70's).

To write a program you had to use a keypunch machine that punched holes in cards, with each line of code going on one card. The whole program was a stack of cards that you submitted to someone at the computer center. That person would run the card deck through a reader, which wrote to a reel-mounted tape. After a few programs (jobs) were written to the tape, the tape was taken over to the computer, mounted, and run.

Most of my programs didn't run, of course, because I didn't know what I was doing. The output I got back (several days later) was on really wide computer paper, with my program code and a bunch of incomprehensible gibberish. I managed to do OK in the class, though, probably ending up with a B or so.

Ten or twelve years later, when PCs were becoming available, and you could get compilers that ran on them, it was a whole different story for me. I could compile my code and get immediate feedback about what was wrong, and make fixes so that the program would at least compile with no errors, if not run correctly. With a debugger I could see exactly what was going wrong. A good debugger is like a window into the heart of the computer - you can see all of the registers of the CPU, all the variables, all of memory, plus a lot more, including the actual operations that the CPU is performing.

For sure this class was extremely frustrating for you, in part due to the shortness of the semester and how long it took you to realize that getting good at programming comes about by writing code, and less so by looking at examples in books. Being able to write code is a very useful and valuable skill to have for anyone in the sciences, so try to keep an open mind. If you were to give it another shot after a while, I'm sure you would do a lot better, and you might find that with less frustration you might even enjoy it.
 
  • #44
I heard about how programs were written back then and that would have been a nightmare for me, no wonder you didn't like it. After being subjected to that, you probably find modern programming fun and relaxing.

I just don't like dealing with computers, honestly. I've messed around with hardware too when I was studying for my A+ certification, and I hated that too.

I'll use a computer for the internet, but other than that I'll stick with the natural sciences.

I may change my mind later, but the frustration of not comprehending it really gets to me.

Thanks again for all your help and spending so much time without giving up. Dealing with this is frustrating for me, but I bet dealing with me is pretty frustrating too.
 
  • #45
Leroy, I just found a bug that you may have discovered by now. In case 4 of of your switch statement, where you need to sort your array's elements, "list[50]" means "the 50th element of the list." It does not mean "This list as 50 elements." Fifty may not be the list length. Depending on how many elements you made room for when you declared the array, the array might even be too small to hold that many elements. If it is to small for that many, the computer probably will complain that a subscript is outside the array's bounds. I'm leaving this message board. So if I may help you in any way, please e-mail me at <personal info deleted by PM staff>.
 
Last edited by a moderator:
  • #46
Well I just found out I got a C. Not even a C- but a C. So thanks for helping me get through this class guys, especially you, Mark. I really appreciate it.
 
  • #47
Everyone,

Maybe I made a mistake. I told Leroy that "list[50]" meant "the fiftieth element of the list." But if the array can hold 50 or more elements, a fiftieth one would belong in list[49] because in C++, array indexing begins at zero.

Bill
 
Back
Top