Understand function call, scope of variables
Passing by value, passing by reference
Become familiar with string library functions
Lectures 16 & 17 on function call and strings
FER Chapter 5, 9, 13, 15
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
string library
Two dimensional arrays
Function call (call-by-value)
Function prototypes
Write the output of each of the codes on the answersheet.
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]);
}
________________ ______________________
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);
}
___________________________________
____________________________
___________________________________
___________________________________
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);
}
_____________________________________________________
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);
}
_____________________________________________________
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);
}
_____________________________________________________
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);
}
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);
}
_____________________________________________________
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);
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);
}
_______________________________________
_______________________________________
_______________________________________
_______________________________________
_______________________________________
Answer Question #1 on the answer sheet.
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 .
Use gedit to open the skeleton source file 'lab10.c' as your starting point.
When compiling, name your
executable file 'lab10' by using the
-o switch, e.g. at the Unix prompt
type,
> gcc lab10.c -o lab10
and if you don't have any error messages, run your program by
typing,
> ./lab10
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 :
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.
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.
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.
So inputWords looks like this,
while( EOF != fscanf(ptr,"%s",words[count]))
++count;
return count;
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 function inputWords has one input parameter, an array named words. You should NOT declare this array again in your code.
To store the words ( strings), we have declared (in main) a 2-dimensional array of characters named words. The code in lab10.h shows that the user must not enter more than 1000 words, and each word is at most 64 letters. For your convenience, we defined MAX_COUNT and MAX_LENGTH in lab10.h. (Why is MAX_LENGTH defined as (64+1) instead of 64?)
We are using a variation of the scanf function called fscanf (file scanf) to read data from a file named "illini.txt". We will NOT have to use Unix redirection (<) .
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!
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.
Declare a local integer num , which will will hold the number of matches. Initialize it to 0.
Declare a variable named target of data type string.
Prompt the user to enter a target string, with which he/she wants to search for an exact match.
Use a single scanf statement to read the string into target.
Write a for loop to search for exact match between the entered words and a target string. To compare two strings, use strcmp function declared in string.h. The strcmp function returns 0 if two strings are the same, and non-zero value otherwise. If there is an exact match, increment a local counter num. Detailed explanation about strcmp can be found here.
After the for loop, print out the count of the number of exact matches using a printf statement. You can remove the comments and complete the call to the printf function.
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.
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'.
Declare a local integer variable num , which will serve as a counter. Initialize it to 0.
Declare a char array named target of length MAX_LENGTH.
Prompt the user to enter a keyword string, with which he/she wants to search for a partial match.
Use a single scanf statement to read the string into the array target.
Write a for loop to search for partial match between the
entered strings and a keyword string. To compare two
strings, use strstr function
declared in string.h. The function strstr(string1,string2)
returns NULL (0) if string2 is
an empty string or string2 is
not found in string1, and
non-zero value if string1
contains string2. If there is a
partial match, increment a local counter num. Detailed explanation about strstr can be found here.
For example,
if (strstr(words[i],target) != NULL)
++num;
After the for loop, print out the counter. You can remove the comments and complete the call to the printf function.
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.
The last function is calculateMeanLength. This function calculates the average length of all the words in the file illini.txt .
Declare a local double variable total , which will calculate the sum of lengths. Initialize it to 0.0 . Note that it should be declared as double (not integer.)
Write a for loop to calculate the sum of lengths. For
each interation, add the length of each string. To get the
length of a string, use strlen
function declared in string.h. The strlen
function returns the length of the string. Detailed
explanation about strlen can be
found here.
For example,
for(i=0;i<count;++i)
total += strlen(words[i]);
After the for loop, use the printf function to print the average. To calculate the average length, which equals the sum divided by the variable count, which stores the number of entered strings.
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!