Lab Activity 10

Objectives


References


Part 1: Prelab

If you are not sure of the answer you may go to any EWS lab on campus and check your results by using the gcc compiler, or you can ask anyone of the CS101 staff for help.

In this prelab, you'll demonstrate your knowledge regarding

Write the output of each of the codes on the answersheet.

  1. Write the output when the following program executes.

    #include <stdio.h>

    void main(void)
    {
      int a[2][3]={1,2,3,4,5,6};

      printf(" %i %i \n", a[0][0], a[1][0]);
    }


    ________________ ______________________

        
  2. The following program compiles and runs without errors. Write the output the program produces.

            #include <stdio.h>
            void main(void)
            {
              char string1[] = {'H','e','l','l','o','\n'};  /* Is '\n' the NULL character? */
              char string2[] = "Hello";  
              int result = strcmp(string1,string2);
              if (result == 0)
                 printf("Equal!");
              else
                 printf("Not equal!");
              printf("\n");
              if( strcmp("Hello", string2) == 0)
                printf("Equal!");
              else
                printf("Not equal!");
              printf("\n%s",string1);
              printf("%s\n",string2);
            }

    ___________________________________

    ____________________________

    ___________________________________
    ___________________________________
        
  3. Write the output when the following program executes.

     #include <stdio.h> 
     
     int cool(int x) 
     {
        x = 2*x; 
        return x; 
     }
       
      
     void main(void) 
     {
        int x = 6; 
        x = cool(x);
        printf("%i \n", x);
     } 
     
      _____________________________________________________ 
     
      
  4. Write the output when the following program executes.

    #include <stdio.h>

    int cooler(int y)
    {
        y = -1*y;
        return y;
    }


    void main(void)
    {
         int x = 6;
         x = cooler(x);
         printf("%i \n", x);
    }


    _____________________________________________________


  5. Write the outptut when the following program executes.

    #include <stdio.h>

    int coolest(int i)
    {
       int x = 9;
       return x + i;
    }

    void main(void)
    {
        int i = 6 , x = 1;
        int z = coolest(i);

        printf("%i %i %i \n", i , x , z);
    }

    _____________________________________________________

  6. Complete the following program that prompts a user for her first name and then reads the name and responds with a personal greeting.
    For example:
    Enter your first name: Sue
    Hello Sue !

    #include <stdio.h>
    #include <string.h>

    void main(void)
    {
       char fname[72];
       char greeting[132];
       printf("Enter your first name: ");


       scanf("%s", ________________________________);
       strcpy(greeting , "Hello ");
       strcat(greeting , fname);
       strcat(greeting , " !");
       printf(" %s \n", greeting);
    }

  7. Write the output when the following program executes. #include <stdio.h>


    #include <stdio.h>

    float addTen(float x)
    {
      float i = 10.0;
      return x + i;
    }

    void main(void)
    {
       float i;
       i = 2.1;
       printf("%f %f \n", addTen(i), i);
    }

    _____________________________________________________

  8. Given code for the function named 'addTen' below, circle(underline) all valid prototypes(there may be more than one correct answer). See lecture 16&17 slides 18-21.

      int addTen(int x) 
      {
        return x + 10;
      } 
         a. int addTen(int x[ ]);
         b. int addTen(int y); 
         c. int AddTen( int); 
         d. void plus_ten( int);
        
  9. Write the output the following program produces when run. See lecture 15-21.

          #include <stdio.h>
          #include <string.h>
          void main(void)  
          {
            char band[32] = "GreenDay";
            char member[32] = {'B','I','L','\0','I','E','\0'};
            printf("%s \n", band);
            printf("%s \n", member);
            printf("%c \n", member[0]);
            strcpy(member, band);
            printf("%s \n", band);
          }


    _______________________________________

    _______________________________________

    _______________________________________

    _______________________________________


    _______________________________________





Part 2: Function call (pass by value and pass by reference)

Answer Question #1 on the answer sheet.

Part 3: String Matching and Statistics

1. Requirements Specification (Problem Definition)
In this lab, you will write several functions which will allow you to match strings, and calculate simple statistics.

In Unix use the mkdir command to create a directory named lab10. Use the cd command to make lab10 your pwd. Use the Unix cp command to copy three files named 'lab10.c', 'lab10.h' and 'illini.txt' into your lab10 directory (files are located in the ~cs101ta/public_html/labs/lab10 directory).

> cd
> mkdir lab10
> cd lab10
> cp ~cs101ta/public_html/labs/lab10/lab10.c . you must type the period at the end of all three commands
> cp ~cs101ta/public_html/labs/lab10/lab10.h .
> cp ~cs101ta/public_html/labs/lab10/illini.txt .

Note: not all the details of the code are listed in the steps below. For example, if you code a loop that uses the variable 'i' then it is assumed that you know that you must declare this variable in your function.

You will not have to write any prototypes since this has already been done for you.
Use gedit to open the file 'lab10.h' (do not change anything in this file) and notice that the prototypes for all functions in this lab have already been typed for you.

Why should you use the lab10.h file?
Many practical programs consist of more than one function, and each might be coded in different .c files. To make sure that the entire program shares a consistent set of functions (names of functions, data type of the input parameters etc) and data structures, we create a header file (a .h file) and put all the function prototypes, as well as commonly used constants in that file. This is the case for MP2. In this lab, we'll use a header file lab10.h to give you practice in reading .h files containing prototypes and constants.

Since C (and Unix) is case sensitive, it is best to copy all the function prototypes from the .h file to your actual .c file to start implementing the functions. That will ensure that you are using exactly the same function names (e.g. showMenu, not showmenu nor ShowMenu), and you have the data type for each parameter as well as the return value ready.



2. Analysis---Refine, Generalize, Decompose the problem definition

The input for this program will come from two sources. Input will come from a keyboard. We will display a menu and request an integer response. The scanf function will be used to read the users response. We will also read words from a file. To do this we will use a new function named fscanf. The fscanf fuction requires the use of pointers. Since we haven't covered pointers in lectures yet all code for the fscanf function has been written for you already.


3. Design---Develop Algorithm

The program can be broken into the following steps :

  1. Complete the code for the function showMenu that shows the main menu, and returns any input from the user. The following is our menu:

    Main Menu
    ----------
    1. Input words
    2. Display words
    3. Search for an exact match
    4. Search for a partial match
    5. Calculate the average length
    0. Exit

    Please enter a choice :


    Note: You will need to add a scanf to read the response the user types from the keyboard.

  2. Add the code below to the main function. In the infinite loop, you call showMenu first, and call appropriate functions according to the return value of showMenu. The switch will be completed later as you complete each of the other functions. For now just add a case 0: option to the switch statement. You can assume that the user will only input integer value. Also, ignore the input other than 0-5, which means that you can show the menu again if the user enter the value greater than 5.

    Add a case 0: to the switch statement, when user enters 0, terminate the program by typing return;. Don't forget to use the break; statement in the switch after every case.

    So main looks like this...

        
        while(1) 
        {
            response = showMenu();
           switch(response) 
            {
        
            /* your code goes here */
            
            } /* end of switch */
        
        
        } /* end of while */


    Save and compile your code. Run your program. At this point you will see a menu but since you haven't completed the switch statement your code will only respond to user response 0.

  3. The first function is inputWords, which reads words from a file into an array named words. Copy the code below into inputWords, and declare any necessary variables.

Don't forget to update main to call inputWords in the switch statement.
The function inputWords returns a value, count, so you will need to assign the value that inputWords returns to the variable named count in main .


    Note:

The second function displayWords has been coded for you. Update main to call displayWords in the switch statement for case 2.
Save, compile and run your program now. Select menu option 1 and next option 2. It you get an infinite loop (possibly by forgetting the break in the switch statement) type Control-c at the keyboard. You may have to type Control-c MANY times. You should see a list of words, the last ten being,

we

pledge

our

heart

and

hand,

Dear

Alma

Mater,

Illinois!

  1. The third function is exactMatch. The function exactMatch counts how many times a certain target word appears. The user will provide the target word. The input parameters are count and words. Do not declare these again in your code.



    Don't forget to update main to call exactMatch the switch statement.
    Save, compile and run your program and test if this option works correctly.

  2. The fourth function is partialMatch. This function works in a similar way to the previous one (you should be able to copy and paste the code in gedit to save you some typing). The function partialMatch finds out not only the number of exact matches to a target string the user supplies, but also the number of partial matches. For example, 'in' is a substring of the string 'spin' and so we will count 'in' to be partially matched with 'spin'. However since 'spin' is not a substring of 'in' then 'spin' is not a partial match of 'in'.

    Don't forget to update main to call partialMatch in the switch statement.
    Save, compile and run your program and test if this option works correctly.

  3. The last function is calculateMeanLength. This function calculates the average length of all the words in the file illini.txt .


    Don't forget to update main to call calculateMeanLength in the switch statement.


    4. Implementation --- Write the "Program" (Code)

    Use the pseudo-code above and open gedit to type your code in the appropriate function in the file named lab10.c that you copied from the directory ~cs101ta/public_html/labs/lab10 .


    5. Run the code

    Save, compile and run your program and test if this option works correctly.

    Now it's time to fill in the blanks on your answer sheet.


    Answer questions #2, #3, #4 on the answer sheet.


    Congratulations! You're done with Lab 10!