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.
  • #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;
    [color="red"]int last[50];[/color]
    
    first = 0;
    last = end;
    while (first <= last)
        {
            [color="red"]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.
 
Technology news on Phys.org
  • #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
 
<h2>1. What is a menu driven search and sort program?</h2><p>A menu driven search and sort program is a computer program that allows users to search and sort data in a structured and organized manner through a menu interface. It typically includes options for searching and sorting by different criteria, such as alphabetical order, numerical order, or specific keywords.</p><h2>2. How does a menu driven search and sort program work?</h2><p>A menu driven search and sort program works by presenting the user with a menu of options to choose from. Once the user selects an option, the program will prompt them for any additional information needed to complete the search or sort. The program then uses algorithms to search or sort the data according to the user's chosen criteria.</p><h2>3. What are the benefits of using a menu driven search and sort program?</h2><p>Menu driven search and sort programs offer several benefits, including improved organization and efficiency in managing large amounts of data. They also allow for more precise and specific searches, making it easier to find the desired information quickly.</p><h2>4. Are there any limitations to using a menu driven search and sort program?</h2><p>One limitation of menu driven search and sort programs is that they may only be able to search and sort data in a specific format or structure. Additionally, the program may not be able to handle very large data sets efficiently, leading to slower search and sort times.</p><h2>5. Can a menu driven search and sort program be customized for specific needs?</h2><p>Yes, a menu driven search and sort program can be customized to fit the specific needs of the user or organization. This can include adding or removing search and sort options, as well as modifying the program's algorithms to better suit the data being searched or sorted.</p>

1. What is a menu driven search and sort program?

A menu driven search and sort program is a computer program that allows users to search and sort data in a structured and organized manner through a menu interface. It typically includes options for searching and sorting by different criteria, such as alphabetical order, numerical order, or specific keywords.

2. How does a menu driven search and sort program work?

A menu driven search and sort program works by presenting the user with a menu of options to choose from. Once the user selects an option, the program will prompt them for any additional information needed to complete the search or sort. The program then uses algorithms to search or sort the data according to the user's chosen criteria.

3. What are the benefits of using a menu driven search and sort program?

Menu driven search and sort programs offer several benefits, including improved organization and efficiency in managing large amounts of data. They also allow for more precise and specific searches, making it easier to find the desired information quickly.

4. Are there any limitations to using a menu driven search and sort program?

One limitation of menu driven search and sort programs is that they may only be able to search and sort data in a specific format or structure. Additionally, the program may not be able to handle very large data sets efficiently, leading to slower search and sort times.

5. Can a menu driven search and sort program be customized for specific needs?

Yes, a menu driven search and sort program can be customized to fit the specific needs of the user or organization. This can include adding or removing search and sort options, as well as modifying the program's algorithms to better suit the data being searched or sorted.

Similar threads

  • Programming and Computer Science
Replies
2
Views
523
  • Programming and Computer Science
Replies
1
Views
895
  • 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
846
  • Engineering and Comp Sci Homework Help
Replies
4
Views
879
  • Programming and Computer Science
Replies
17
Views
2K
  • Programming and Computer Science
Replies
5
Views
3K
Back
Top