Skip to main content
Logo image

Section 22.1 Linear Search

There are many reasons for wanting to sort and/or search lists of data:
  • Look for a student record in a list of records
  • Print alphabetically sorted list of names
  • Sort data values in ascending/descending order
  • And many more!
We’ll start by introducing a very simple algorithm, called linear search, to search for a specific item in a list of items.

If you cannot see this codecast, please click here.

Check Your Understanding Check Your Understanding

1.

    Quick review question: Which of the following is the correct way to declare and initialize a string?
  • char name[] = "cool_file_name";
    
  • Correct
  • char name[50]; name = "cool_file_name";
    
  • Not quite. Try again!
  • char name = "cool_file_name";
    
  • Not quite. Try again!
  • char = "cool_file_name"[50];
    
  • Not quite. Try again!

2.

    More review: Is there anything wrong with the following:
    char name[10];
    . . . 
    strcpy(name, "TodayIsMonday");
    
  • This will overwrite memory cells that have not been reserved for name.
  • Correct
  • It should be
    strcpy("name", TodayIsMonday);
    
  • Not quite. Try again!
  • It should be
    strcpy(“TodayIsMonday”, name);
    
  • Not quite. Try again!
  • No, nothing wrong.
  • Not quite. Try again!

3.

    Even more review: What is the result of the following:
    strcmp("my_apple", "my_banana");
    
    Feel free to use the window below to try out some code. Be sure to work the correct answer out "by hand" first before verifying your answer using the code window.

    admin.....open in new window

  • a negative number
  • Correct
  • the letter ’b’
  • Not quite. Try again!
  • a positive number
  • Not quite. Try again!
  • zero
  • Not quite. Try again!
  • the letter ’a’
  • Not quite. Try again!

4.

    Final review question (I promise!): Suppose a string has been declared as follows:
    char food[30];
    
    You want the user to enter their favorite food and store the response in the string food. What is the correct command to do so?
    Feel free to use the window below to try out some code. Be sure to work the correct answer out "by hand" first before verifying your answer using the code window.

    admin.....open in new window

  • scanf("%s", &food);
    
  • Correct
  • scanf("%s", food[0]);
    
  • Not quite. Try again!
  • scanf("%s", food);
    
  • Not quite. Try again!
  • scanf("%s", *food);
    
  • Not quite. Try again!