basicdatastructures studyguide

Upload: richard-mcdaniel

Post on 12-Oct-2015

57 views

Category:

Documents


0 download

DESCRIPTION

BasicDataStructures StudyGuide

TRANSCRIPT

  • 5/22/2018 BasicDataStructures StudyGuide

    1/51

    1/9/1Introduction

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/intro.html

    Introduction

    In CS 9C, you learn to program in C. You are assumed to have had previous programmingexperience, in particular with the construct called apointerin Pascal or Scheme or an addressinassembly language. CS 3 or 3S or IDS 110 probably does not provide sufficient experience forthis course; we recommend that you take CS 9B to acquire more experience.

    Course material consists of quizzes, which test your knowledge of language and low-levelconceptual details, and programming assignments, which exercise your overall command of thelanguage. This volume supplies a framework for the course. It contains the following:

    Study modules. Each module focuses on a particular programming topic.It provides references totextbook material describing the topic,and suggests exercises for self-study. The study guidesreference the following texts and documents.

    Beginning with C, Ron House (PWS Publishing Company, 1994).

    The C Programming Language, second edition, B.W. Kernighan and D.M. Ritchie(Prentice-Hall, 1988).

    Programming assignments. Each one has a header page (this tells you the title and related topics)that is followed by the actual assignment.

    Sample quiz questions, with solutions. These help you prepare for the quizzes.

    Comments on the texts

    The House book is aimed at programmers without a lot of experience. If you have had only acouple of courses prior to CS 9C, or you haven't written many programs that use pointers, youwill benefit from the explanations and extended examples in this text.

    The Kernighan and Ritchie book (affectionately known as "K and R") is the "bible" for the Clanguage. It was written for experienced programmers; once you learn C, you will find it anexcellent reference.

  • 5/22/2018 BasicDataStructures StudyGuide

    2/51

    1/9/1Structure of quizzes and programs in CS 9C

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/course.org.html

    Structure of quizzes and

    programs in CS 9C

    The following table outlines the relationship between quizzes and programs. All the material fora particular grouping should be completed before material in the next grouping; however, you

    must complete the corresponding program before taking any quiz.

    group programs quizzes

    a

    Orientation

    Introduction

    Debugging

    Fundamentals

    Functions and argument pointers

    b Abstract data types with arraysArrays, structures, and files

    General pointers

    c Abstract data types with trees Linked structures

    For information about deadlines, consult the "Information and Regulations" document.

  • 5/22/2018 BasicDataStructures StudyGuide

    3/51

    1/9/1Program Introduction

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.intro.html

    Program Introduction

    This programming assignment introduces you to C: variables and computation, functions andparameters, and control structures. (You are allowed to use arrays as well if you want. However,they are not required, nor are they necessary to solve the problem)

    The C compiler provided on the EECS instructional computer accounts is named gcc. It comeswith a debugger gdb, which not only is a great debugger but has an extensive online help facility.It supports ANSI Standard C as described in House and the second edition of Kernighan andRitchie. Use gccto compile the program piglatin.cfor this assignment as follows:

    gcc -g -Wall -o piglatin piglatin.c

    (On the EECS instructional computers, the gcccommand is probably set up to supply the "-g"and "-Wall" information automatically. To make sure of this, type

    alias

    to the UNIX shell and look for an entry for gcc.)

    If the program contains no syntax errors, this command will produce an executable file namedpiglatin. To run the program under control of the debugger, type the command

    gdb piglatin

    Running your program in this way is useful to simplify the task of tracking down your executionerrors; for example, if your program crashes, gdbwill tell you the line number where the

    problem occurred. You'll learn more about gdbin the next programming assignment.

    Readings

    House, chapters 1 through 8 except material in chapters 3, 5, and 7 on arrays.

    Kernighan and Ritchie, chapters 1 through 4 except sections 1.9, 1.10, 3.8, 4.3, 4.5, 4.6, 4.7,4.10, 4.11.2, and 4.11.3. You will not be tested on material on arrays in chapters 2 through 4.

    The section "Before You Begin ..." available online in the self-paced course web site (forstudents who are not familiar with EECS computing facilities).

    The section "C Style Examples" later in this document.

    Related quizzes

    Fundamentals of C

    CS 9C programming assignment 1

  • 5/22/2018 BasicDataStructures StudyGuide

    4/51

    1/9/1Program Introduction

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.intro.html

    Pig Latin

    Background

    Pig Latin is a language parents speak to each other when they don't want their children tounderstand them. Each English word has a Pig Latin translation; you produce it as follows.

    1. If the English word begins with a vowel ("a", "e", "i", "o", "u"), add "yay"to the end of theword to produce the Pig Latin translation.

    2. If the English word begins with a consonant (a non-vowel), move all leading consonants tothe end of the word and add "ay" to produce the Pig Latin translation. You should treat theletter `y' as a vowel when it occurs after the first character in a word. You should also treatthe letter pair "qu" together as a consonant. Here are some examples.

    English Pig Latin

    yes esyay

    example exampleyay

    bygone ygonebay

    test esttay

    quiz izquay

    strip ipstray

    trips ipstray

    schnitzel itzelschnay

    rhyme ymerhay

    Problem

    Write a program in C to read a word from standard input and print its Pig Latin translation on aline by itself on standard output. You may assume that an English word starts with no more thanfour consonants.

    Miscellaneous requirements

    Guidelines for indenting, commenting, etc. are indicated in the section "C Style Examples".Follow them.

    C code is rather dense. Thus your functions should be small, certainly at most a screenful ofcode.

    Your program need not use arrays. You may assume that an English word starts with no more

  • 5/22/2018 BasicDataStructures StudyGuide

    5/51

    1/9/1Program Introduction

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.intro.html

    than four consonants. (This assumption makes it possible to avoid arrays.) You may also assumethat each "q" is followed by a "u". Test your program at least on the examples given above.

    System information

    The line#include at the start of your program will allow you to use the predefinedconstant EOFand the getcharand putcharroutines for input and output.

    There is a program called unpigin the ~cs9c/libdirectory on your class account. After readinga word, unpigprints all possible English words (and a few non-English "words") that have thatword as a Pig Latin translation. You may use unpigto check your work by piping your outputinto it. (unpigdoesn't quite work correctly for words starting with "qu", however.)

    Generating a transcript of your program execution

    For this and all remaining assignments, you are required to bring a transcript of your interactionwith your program to the Self-Paced Center for grading. One way to create such a transcript on

    UNIX is to use the scriptprogram, which saves everything you do on the terminal in a file,called typescript, until you type the command exit. After you are done, you can get a paperprintout of this file by using thelprcommand. Here is an example of using thescriptandlprcommands for this assignment:

    % script Script started, file is typescript % cat prog1.c

    ... (your program listing) ...

    % gcc prog1.c

    % a.out yes esyay % a.out | unpig strip ripst trips strip pstri % exit % Script done, file is typescript

    Everything that has appeared on the terminal between the scriptcommand and the exitcommand has been saved in the file called typescript. You can now type lp typescriptto geta paper printout to bring in to the Self-Paced Center after you have done the rest of theassignment.

    Do nottype another scriptcommand without first typing exit.

    Do notusean editor when you are using script. While this does no harm, it does put bizarrecharacters into the typescript file that cannot be displayed properly. If you do this your printout

  • 5/22/2018 BasicDataStructures StudyGuide

    6/51

    1/9/1Program Introduction

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.intro.html

    will end up being very garbled.

    Helpful hints

    C gives you plenty of rope to hang yourself. To save your neck, you should spend timedecomposing the problem into manageable pieces (i.e. separate functions!) before trying tocode anything, and then test each piece separately. You may test your functions individually by

    writing a tiny "driver" main ( )that simply gets test data and calls the function.

    Some aspects of C are sure to trip up the novice C programmer, for instance, the placement ofsemicolons and parentheses, the need to "break" out of a case in a switchstatement, and theindexing of arrays. The compiler and run-time system are sometimes of little help in findingthese errors. Advice: Start with something simple, get it working, and add small pieces to it oneat a time. Tutors will ask you, when you bring them bugs, "What was the last thing you did thatworked?" You should have a good answer.

    Arrays are not necessary for this problem. (Why? If you need a hint, consider a program thatsimply echoes characters from the standard input to standard output. How many variables doesthat program need?)

    Checklist

    A satisfactory grade on this assignment requires the following:

    Correctly working program, tested as suggestedShort functionsGood style and layoutReasonable names for variables, functions, etc.

    Loops and blocks indented according to the given guidelinesInformative comments accompanying every function

    MJC, EL 8/95

  • 5/22/2018 BasicDataStructures StudyGuide

    7/51

    1/9/1QuizFundamentals

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.fundamentals.html

    Quiz Fundamentals

    This quiz focuses on the aspects of the C language that are conceptually similar to those in otherprocedural languages: variable declaration, expression evaluation, flow-of-control constructs,and input/output. Three especially tricky aspects of C covered on this quiz are the differencebetween = and ==, the difference between charand intvalues, and the representation of "true"and "false".

    Readings

    House, chapters 1 through 6 except material in chapters 3, 5, and 7 on arrays. House omits thetype of themainfunction throughout; in contrast, we will always specify it as type intinaccordance with the C standard. (By convention, a return value of 0 from themainfunctionmeans successful completion; nonzero return values indicate some sort of error.)

    Kernighan and Ritchie, sections 1.1 through 1.6; chapters 2 and 3 except material on arrays and

    functions.

    Suggested exercises

    House, "short answer" self-test exercises and test questions in chapters 2 through 6 exceptsection 5.7 #2 and #7. You may also be asked to write small program segments.

    Sample quiz

    1. Suppose that an integer variable ncontains the value 80. Fill in the blanks in the printf

    statement below so that it produces the output

    80% usually means "excellent"

    printfstatement:

    printf ("________", n);

    2. Consider the program segment

    int k; k = getchar ( ); printf ("%d", k);

    What gets printed if the user types a 2, then hits return?

    3. The following program is intended to compute 5! = 120, but it prints 24 instead. What'swrong with it?

    int main ( ) {

  • 5/22/2018 BasicDataStructures StudyGuide

    8/51

    1/9/1QuizFundamentals

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.fundamentals.html

    int theNum, total; total = 1; theNum = 5; while (theNum > 1) { total *= --theNum; } printf ("%d", total); return 0; }

    4. What would be the effect of substituting !(theNum = 1)for thewhilecondition theNum >1in the main program of exercise 3?

    5. Fill in the blanks in the code below to convert thewhileloop in exercise 3 to an equivalentforloop.

    int main ( ) { int theNum, total; total = 1; for ( _____ ; _____ ; _____ ) {

    total *= theNum; } printf ("%d", total); return 0; }

    6. Write down the values for all variables appearing in each statement.

    int main ( ) { int x, y, z; float a, b; x = 3; y = 5.3; z = 2; x ____ y ____ z ____ a = 2.5; b = 3.14; a ____ b ____

    /*1*/ x += y + a * z-b; x ____ /*2*/ a = b / (x%y + z) a ____ z += (x == y); z ____ /*3*/ x == (a = b); x ____ return 0; }

    Where do you need parentheses to have xassigned a value of 14 in the statementlabeled /*1*/? What then is the new value of ain the statement labeled /*2*/? Whatis the new value of xin the statement labeled /*3*/?

    7. Predict the output of the following program. Hint: only three lines get printed. (This issomewhat more complicated than any of the actual quiz questions.)

    int main ( ) { char c; for (c='a'; c

  • 5/22/2018 BasicDataStructures StudyGuide

    9/51

    1/9/1QuizFundamentals

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.fundamentals.html

    printf ("%c\n" , c-- ); default: ++c; } printf ("*** %c\n" , c); } return 0; }

  • 5/22/2018 BasicDataStructures StudyGuide

    10/51

    1/9/1Program-Debugging

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.debugging.html

    Program Debugging

    No doubt the program for the previous programming assignment gave you some practice in debugging. This assignment will give you more. You are to findsome bugs we've installed in a program. gdbwill again be helpful.

    Readings

    House, chapter 8; sections 9.1 through 9.4, 12.1, and 12.2.

    Kernighan and Ritchie, material on arrays in chapters 1 through 4 that you didn't read for the "Fundamentals" quiz, plus sections 5.1 through 5.3. Material isections 1.10, 3.8, 4.3, 4.5, 4.6, 4.7, 4.10, 4.11.2, and 4.11.3 will not be covered.

    Related quizzes

    Simple strings and pointers.

    Background

    This assignment provides an introduction to some of the major features of gdb(the GNU debugger) by leading you through the debugging process of aslightly buggy program. A debugger allows the programmer to stop a program in the middle of its execution so that he or she may observe how the programbranches and executes. Debuggers can help speed the process of isolating and correcting bugs.

    Follow the instructions outlined in the assignment in order to debug the provided program and answer the questions throughout the assignment on a separatpiece of paper. You will be required to present the corrected code, script files (to be explained later), and answers to the questions in this assignment. Thequestions in this assignment are meant to be thought-provoking. They illustrate important aspects of the C language. If you experience problems, do not

    hesitate to ask a tutor for help!

    Students who do not wish to use gdbor students who use their own development package (Borland C, etc.) will need to follow the steps dictated in theinstructions and demonstrate identical functionality in the debugger of their choice (e.g., via screenshots). If you can't provide such documentation, you wilneed to use gdb.

    The code associated with this assignment is a short program whose purpose is to turn regular phone numbers into "words." For example, the Federal Exprescustomer service number is 1-800-GO-FED-EX, translated from 1-800-46-333-39. The provided program, when working properly, will provide all possible"words" that have no more than a user-specified number of consonants. (Too many consonants may make the "word" unpronounceable.) Below is a transcriof how the program should work, with user input appearing in boldface:

    This program finds words that can be associated with phone numbers. What is the maximum number of consonants you would like the generated word to possess? (note: 0's and 1's are considered consonants) 4 Please enter a 7 digit phone number with dashes removed 4460175

    iio01pj iio01pk iio01pl iio01rj iio01rk iio01rl iio01sj iio01sk iio01sl iio01pj iio01pk iio01pl iio01rj iio01rk iio01rl iio01sj iio01sk iio01sl iio01pj iio01pk iio01pl iio01rj iio01rk iio01rl iio01sj iio01sk iio01sl iio01pj iio01pk iio01pl iio01rj iio01rk iio01rl iio01sj iio01sk iio01sl iio01pj iio01pk iio01pl iio01rj iio01rk iio01rl iio01sj iio01sk iio01sl iio01pj iio01pk iio01pl iio01rj iio01rk iio01rl iio01sj iio01sk iio01sl iio01pj iio01pk iio01pl iio01rj iio01rk iio01rl iio01sj iio01sk iio01sl iio01pj iio01pk iio01pl iio01rj iio01rk iio01rl iio01sj iio01sk iio01sl iio01pj iio01pk iio01pl iio01rj iio01rk iio01rl iio01sj iio01sk iio01sl Would you like to try another number? (Y/N) n

    Before continuing on with this assignment, make sure you have done all of the associated reading and understand how the code we've provided should workThe program can be found in the file ~cs9c/lib/generate.c.

    Assignment

    The first step in the debugging process is the compilation of the program. In the process of compiling code, useful error messages are provided that identifyproblematic parts of the code that are not syntactically correct. Very often, these mistakes are typos.

    If you haven't done so already, copy the file into your own directory using the following command:

    % cp ~cs9c/lib/generate.c . (don't forget the dot!)

    To compile the program type:

    % gcc generate.c1

    You should see something similar to the following (your output may not be exactly the same):

  • 5/22/2018 BasicDataStructures StudyGuide

    11/51

    1/9/1Program-Debugging

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.debugging.html

    generate.c: In function 'main': generate.c:54: parse error before 'puts' generate.c: In function 'print_if_good': generate.c:210: warning: value computed is not used generate.c: At top level: generate.c:231: warning: return-type defaults to 'int' generate.c:231: conflicting types for 'convert' generate.c:9: previous declaration of 'convert' generate.c: In function 'convert': generate.c:236: warning: control reaches end of non-void function

    The numbers after the filename refer to the numbers of lines that contain errors. "Parse errors" typically signify something that is syntactically incorrect."Warnings" are issued for code that the C compiler believes to be problematic but that is syntactically correct. Warnings will not prevent your code from

    compiling, but they can tip you off to some rather serious problems.

    1. Use the text editor of your choice, correct the errors. (Typing ctrl-Cin Pico or esc-x line-number-modein emacstells you what line you're on.)Make a note of what changes you made. You may need to make small changes and recompile to see if those errors are fixed. This may take severaliterations. It is okay not to fix all the warnings but all of the non-warning problems will need to be fixed.

    If you reach this point:

    generate.c: In function 'print_if_good': generate.c:210: warning: value computed is not used

    Your program has compiled successfully; Don't try to figure out what's wrong with this line yet. We'll figure it out eventually.

    In order to record your debugging session, you will need to use the scriptcommand. The scriptcommand stores the text of your session in a file. Type thfollowing:

    % script assignment2

    Your prompt may change at this point (don't worry). Now all of your interaction with the prompt will be recorded in the file named assignment2.

    Let's see if the program works. To run the compiled program type the following (words you type are in bold):

    % a.out This program finds words associated with phone numbers. What is the maximum number of consonants you would like the generated word to possess? (note: 0's and 1's are considered consonants) 4 Please enter a 7 digit phone number with dashes removed 4460175

    2. The program has one or more bugs. How does the output suggest something is wrong?

    We will now use gdbto begin debugging. To start gdbdebugging this program, type:

    % gdb a.out GDB is free software and you are welcome to distribute copies of it under

    certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for GDB; type "show warranty" for

    details. GDB 4.16 (hppa1.1-hp-hpux9.05), Copyright 1996 Free Software Foundation,

    Inc... (gdb)

    Before we begin running the program, we will need to set a breakpoint. A breakpoint is a programmer-specified point in the code where we would like theprogram to "pause" at while the program is running. Why would we want to do this? Using a debugger, we may examine variables in this paused state whicwill give us important information about whether or not the program is working correctly. Type:

    (gdb) break main Breakpoint 1 at 0x2330: file generate.c, line 42.

    This will ask the program to stop at the first executed line of code of the main ( )function. Variable declarations will be processed immediately. To run thprogram, and have it stop at this point, type:

    (gdb) run Breakpoint 1, main ( ) at generate.c:42 43 goahead = 1;

    Notice that the program has stopped right before it is about to execute a line of code. In this case, the line of code in question is line 43 (your output mayvary). To see this, let's find out what the value of goaheadis. Type the following:

    (gdb) print goahead $1 = -1073785707

    In the above case, the variable goaheadis storing a garbage integer (your output will definitely vary here!). Remember, if you don't assign a variable an init

  • 5/22/2018 BasicDataStructures StudyGuide

    12/51

    1/9/1Program-Debugging

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.debugging.html

    value, its contents will be unpredictable. Now type:

    (gdb) next 44 while (goahead)

    The nextcommand executes the line of code that was stopped at, and then stops the program at the very next line of code. To make sure the assignmentgoahead = 1has actually taken place, we can again view the contents of goahead:

    (gdb) print goahead $2 = 1

    Sometimes we may want to find out the value of a variable after each statement. gdbprovides this functionality in its displaycommand. Type:

    (gdb) display goahead 1: goahead = 1 (gdb) next puts ("This program finds words associated with phone numbers.\n\n"); 1: goahead = 1

    Continue executing the program line by line using the nextcommand. Stop when you see the following:

    57 gets (input); 1: goahead = 1

    Type the following:

    (gdb) display input 2: input = "38!(@#*(#*!(@#1" (gdb) next 4 64 maxNumConsonant = input[0] - '0';

    2: input = "4\000!(@#*(#*!(@#1" 1: goahead = 1

    Notice that the contents of the string inputhas changed. Since strings are null-terminated, when getsreads a string, it copies the user's input into the arraypassed into the function and places a null terminator (denoted by \000 in the display portion) into the array when it reads a carriage return.

    3. Using the techniques you have learned so far, explain what gets copied into maxNumConsonantafter the line above is executed. What gdbcommandsdid you use to find out what was copied into maxNumConsonant? Explain what input[0] - '0'does.

    Continue executing the code line by line until the following is reached2:

    71 generateSpellings (phone, maxNumConsonant);

    generateSpellingsis a defined function within this program. We may be interested in watching what happens within the generateSpellingsfunction. Ifwe type nextat this point, we will go to the next instruction instead of going inside the generateSpellingsfunction. In order to go insidegenerateSpellings, we can use the stepcommand:

    (gdb) step generateSpellings (phone=0x7fffbda8 "4460175", maxNumConsonant=4) at

    generate.c:128 128 char dial[10][4]={

    Several things happen now. First, the variables that you painstakingly "displayed" one by one are no longer refreshed. The reason is because those variablesare not accessible from within the generateSpellingsfunction. The line above shows the contents of the two variables passed into the function: phoneandmaxNumConsonant. Your output may be somewhat different.

    For your information, 0x7fffbda8is the hexadecimal (base 16) equivalent for 2,147,466,664. gdbdenotes memory addresses by the 0xprefix. As you cansee, the hexadecimal format is a more efficient way of representing large numbers.

    4. What is the value stored in phone? (Hint: Everyone's answer will be different.) Why is phonerepresented by an address?

    Continue using the nextcommand until you see:

    144 convert (phone, phone_int);

    Let's step into this function as well:

    (gdb) step convert (phone=0x7fffbda8 "4460175", phone_int=0x7fffbd08) at gener- ate.c:233 251 for (i = 0; i < 7; i++)

    When stepping into a function, gdbdoes not display the contents of an integer array when it is passed in as an argument. This is unlike what it does withcharacter arrays. (Note the difference between phoneand phone_int.) However, regardless of variable type, gdbwill always show you what the value of thvariable is when it is passed into the function. If this doesn't make sense, then you didn't answer question 4 correctly.

    In the next five lines is a forloop. It is often helpful to monitor a forloop's progress. Type the following:

  • 5/22/2018 BasicDataStructures StudyGuide

    13/51

    1/9/1Program-Debugging

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.debugging.html

    (gdb) display i 3: i = 74128 (gdb) display phone_int[0] 4: phone_int[0] = 268530816 (gdb) display phone_int[1] 5: phone_int[1] = 4199972 (gdb) display phone_int[2] 6: phone_int[2] = 8192 (gdb) display phone_int[3] 7: phone_int[3] = 0 (gdb) display phone_int[4] 8: phone_int[4] = 843604063 (gdb) display phone_int[5] 9: phone_int[5] = 0 (gdb) display phone_int[6] 10: phone_int[6] = 268436928

    Again, because values have not been assigned to the array cells above, their contents are in fact completely arbitrary. Your output may differ somewhat.

    Monitoring the forloop's progress generally means stepping through it via repeated stepor nextcommands. In gdb, hitting return re-executes the mostrecent command; this facility simplifies the process of monitoring a long stretch of code.

    5. Use the techniques that you've learned thus far and determine whether or not the forloop in this function works. What evidence suggests so?

    When you exit the function, you should see the following:

    generateSpellings (phone=0x7fffbda8 "4460175", maxNumConsonant=4) at generate.c:152 157 for (a = 0; a < 3; a++)

    The statement above lets you know that you've returned to the calling function (in this case, generateSpellings).

    6. Starting on the above line, a series of nested loops is encountered. How does each nested loop work? Make sure you step through the loop anddemonstrate that you've actually examined how the loop works.

    Continue executing the code line by line until you reach

    176 print_if_good(maxNumConsonant, word, &level);

    7. What is the current value ofword? Which gdbcommand did you use to find its value? Is its value correct?8. In line 176, the address of the variable levelis passed into print_if_goodas opposed to the variable's contents. The comments explain that this is

    technique that allows the function to change the contents of a variable passed into a function. Explain how passing a pointer to a variableaccomplishes this.

    Step into this function using the stepcommand:

    (gdb) step print_if_good (maxNumConsonant=4, word=0x7fffbd48 "ggm01pj",

    level=0x7fffbd50) at generate.c:193 206 int numVowel = 0;

    In the following code, there is a forloop that counts the number of vowels and an ifstatement that determines whether or not the generated word is printeWe are interested in testing what happens when the ifcondition is true. Since we may not enter the condition every time, we could end up typing nextmantimes before we reach the statements within the ifcondition. One way to skip to the "interesting" part of the program is to execute the following command

    (gdb) break 207 (gdb) continue

    In the above gdbstatements, we have asked the program to stop at line 207. Line 207 is the call to printfwithin the ifstatement. The continuestatementtells the program to run at full speed until the next breakpoint is reached-in this case, when we next execute line 207.

    You should eventually see something similar to

    Breakpoint 2, print_if_good (maxNumConsonant=4, word=0x7fffbd48"iio01pj",

    level=0x7fffbd50) at generate.c:207 207 printf ("%s ",word);

    Print the word and go to the next line:

    (gdb) next 210 *level++;

    Now find out what the value of leveland *levelis (your output will vary):

    (gdb) display level

  • 5/22/2018 BasicDataStructures StudyGuide

    14/51

    1/9/1Program-Debugging

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.debugging.html

    11: level = (int *) 0x7fffbd50 (gdb) display *level 12: *level = 0

    The hexadecimal number 0x7fffbd50is 2,147,466,576 in decimal. Let's find out what happens when we execute this line.

    229 if ((*level)%7 == 0) 4: *level = 0 3: level = (int *) 0x7fffbd54

    The value of levelis now 0x7fffbd54or in decimal, 2,147,466,580. *levelis still 0. What result did we expect? It seems like we might have a problemhere.

    9. Explain what the problem is in this section of code. Fix the problem in the code, and recompile the program. What happened to the warning?

    The quitcommand exits gdb.

    When you've recompiled the program, verify the rest of the program works as described. To end your script, type:

    % exit

    You will need to turn in your corrected version of generate.c, the script of your interaction with the debugger, and your answers to the boxed questions inthis assignment.

    Checklist

    A satisfactory grade on this assignment requires the following:

    Corrected version of generate.cScript of debugger interactionAnswers to questions 1 through 9

    HY: 8/

    Buggy program

    #include #include /**************************************************************** Function declarations.*************************************************************** */

    void generateSpellings (char [], int);void convert (char phone[], int* phone_int);void print_if_good (int, char[], int[]);int isvowel (char);

    /****************************************************************main( )input Character array that is used to store user input. Its size is greater than two characters in order to

    accommodate responses such as yes/no and possibly other unpredictable user responses. (See a tutor for an explanation.)phone Character array used to store the actual phone number entered by the user. Space is allocated for seven digits and the corresponding carriage return.maxNumConsonant User-entered value that filters out those numbers with too many consonants.goahead true/false flag that determines whether or not the user wants to test another number.*************************************************************** */

    int main ( ) { int maxNumConsonant; int goahead; char input[8]; char phone[8];

    goahead = 1; while (goahead) { /* This part of the code gathers user data. The use of puts and gets is illustrated here.

    puts sends its char array to standard output followed by a carriage return. gets putseverything in the standard input up to the carriage return into a character array. In placeof the carriage return, puts has a '\0' to signify the end of the string. */

    puts ("This program finds words associated with phone numbers.\n\n"); puts ("phone numbers\n\n")

  • 5/22/2018 BasicDataStructures StudyGuide

    15/51

    1/9/1Program-Debugging

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.debugging.html

    puts("What is the maximum number of consonants you would like"); puts("the generated word to possess?"); puts ("(note: 0's and 1's are considered consonants)"); gets (input);

    /* Each digit read in as a character needs to be converted to a number for comparison pur- poses later. The difference between the ASCII value of the user input and the ASCII value

    of '0' will return the appropriate numeric value for the character. */ maxNumConsonant = input[0] - '0'; puts ("Please enter a 7-digit phone number with dashes removed"); gets (phone);

    /* The generateSpellings function does most of the work. */ generateSpellings (phone, maxNumConsonant); putchar ('\n'); putchar ('\n'); puts ("Would you like to try another number? (Y/N)"); gets (input); if ((input[0] == 'Y') || (input[0] == 'y')) { goahead = 1; } else { goahead = 0; } } return 0;}

    /*****************************************************************generateSpellings (char*, int)phone_int The characters '1', '2', '3', ... are converted to 1, 2, 3, ... and stored appropriately in this

    numeric representation of the user's phone number.

    level This variable is used to make the printouts nice.It is passed using the "address of" operator, as described in House

    in section 5.2.1. Passing a variable using the "address of" operator in this way is a technique that allows a function to

    change its contents in such a way that the changes are recognized in the calling program. Note that level should really be a local variable in generateSpellings; it is used as a parameter here for illustrative purposes.a-g Index variables used to keep track of for loops.word A candidate "word" that is then passed on to print_if_good, which prints the word if it meets the minimum requirements for consonants. The representation is again an array of characters terminated by a NULL ('\0').dial A two-dimensional array. For each dial [i][j], i represents

    the actual number on the key pad (a value between 1 and 10) and j indicates a choice of letter that the key pad could represent.

    So, for example, dial[2][3] would represent thethird letter on button #2 of the keypad, namely the letter "c".

    Similarly, dial[2][2] == 'b', dial [3][3] = 'f', etc.Confused? Pick up your phone and take a look!Some letters aren't mapped the way they should be.Note that the letters "q" and "z" have been removed.The numbers 0 and 1 have no associated letters and sothe program simply returns a "1" or a "0" in those

    circumstances.*************************************************************** */

    void generateSpellings (char* phone, int maxNumConsonant) { int phone_int[7]; int a, b, c, d, e, f, g; char word[8]; int level; char* dial[10] = {"000", "111", "abc", "def", "ghi", "jkl",

    "mno", "prs", "tuv", "wxy"}; /* Each ASCII character stored in phone is converted to its appropriate number. */ level = 0; convert (phone, phone_int); /* The following for loop works as follows: for each of the seven digits in the phone number, we

    generate all the different possible letters each letter can take on by considering each digit inturn until all values are exhausted. */

    for (a = 0; a < 3; a++) { for (b = 0; b < 3; b++) { for (c = 0; c < 3; c++) { for (d = 0; d < 3; d++) { for (e = 0; e < 3; e++) { for (f = 0; f < 3; f++) { for (g = 0; g < 3; g++) { /* The candidate word is built here. Starting with the first le

    the word we assign a candidate translation dial[][a] based on

  • 5/22/2018 BasicDataStructures StudyGuide

    16/51

    1/9/1Program-Debugging

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.debugging.html

    the original number's value. */ word[0] = dial[phone_int[0]][a]; word[1] = dial[phone_int[1]][b]; word[2] = dial[phone_int[2]][c]; word[3] = dial[phone_int[3]][d]; word[4] = dial[phone_int[4]][e]; word[5] = dial[phone_int[5]][f]; word[6] = dial[phone_int[6]][g]; word[7] = '\0'; /* print_if_good prints the word if it meets the minimum

    requirements. */ print_if_good (maxNumConsonant, word, &level) } } } } } } }}

    /* This function prints the word if it has maxNumConsonant or fewer consonants. */void print_if_good (int maxNumConsonant, char* word, int *level) { int i; int numVowel = 0; /* This loop counts the number of vowels. */ for (i = 0; i < 7; i++) { if (isvowel(word[i])) { numVowel++; } }

    /* This loop prints the word if there is maxNumConsonant or fewer consonants. */

    if ((7 - numVowel)

  • 5/22/2018 BasicDataStructures StudyGuide

    17/51

    1/9/1Program-Debugging

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.debugging.html

  • 5/22/2018 BasicDataStructures StudyGuide

    18/51

    1/9/1Quiz-Functions and argument pointers

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.functs.arg.ptrs.html

    Quiz Functions and

    argument pointers

    This quiz covers the definition and use of functions. Details that are tested here include the use ofpointers to allow functions (including scanf) to change values in code that calls them and the use

    of the strcpyand strcmpfunctions accessible through .

    Readings

    House, chapter 7, sections 5.1, 5.2, 5.3, 12.1 and 12.2, and material on in chapters 3and 6.

    Kernighan and Ritchie, chapters 1 through 4 except sections 1.10, 3.8, 4.3, 4.5, 4.6, 4.7, 4.10,4.11.2, and 4.11.3. You will not be tested on material on arrays in chapters 2 through 4.

    Suggested exercises

    House, "short answer" self-test exercises and test questions in chapters 5 and 7. You may also beasked to write small program segments.

    Sample quiz

    1. What is the output of the following program segment?

    c = 'a';

    putchar (c);

    putchar (F(c));

    putchar (c);

    Assume that the function Fhas been defined as follows:

    char F (char c) {

    c = 'f';

    return (c);

    }

    2. Modify the code from exercise 1 so that, on return from the Ffunction, the variable cinthe callingcode contains the character 'f'.

    3. Write a functionAllDonethat, given a string as argument, returns a true value if the stringis "exit"and returns false otherwise.

    4. Write a function GetWordAndValuethat prompts the user for a string and an integer, readsthe values, and returns both to the calling program. Assume that the caller has alreadyprovided space in memory for all the characters of the word.

    5. Write a main program that calls GetWordAndValueand echoes the values returned.

  • 5/22/2018 BasicDataStructures StudyGuide

    19/51

    1/9/1Quiz-Functions and argument pointers

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.functs.arg.ptrs.html

  • 5/22/2018 BasicDataStructures StudyGuide

    20/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    Program Abstract data types

    with trees

    Most of the significant breakthroughs in computing science have been achieved through a process of

    representation, that is to say, changing one's way of perceiving a problem so that it can be solved

    more easily. Structures such as lists, trees, tables and so forth have meaning to us as problemsolvers, but do not have direct existencein the computer. The C structand typedeflanguageconstructs allow programmers to represent more abstract structures in terms of the simple dataobjects built into the language.

    C allows the use of the programmer to isolate the details of the implementation of a data type in asingle file or group of files. By using access functions and header files it is possible for one series offunctions to use a data structure without ever dealing with the actual language primitives that definethe data structure. This use of an abstract data typeis good software engineering; it allows one toimplement and modify the implementation of the data structure with minimal change to the rest ofthe program.

    Careless C programmers often write code with "memory leaks", that is, instances where storage isrequested viamallocand never freed. A process that runs a long time with a memory leak, forexample, a part of the operating system or a process that runs in the background monitoring userinteraction, will eventually leave no room for other programs. This assignment gives you somepractice tracking down these problems.

    Readings

    House, chapters 10, 11, 14, and 15; sections 12.4, 13.2, and 13.3. (It will also be useful to reviewsection 13.1.) Chapter 15 is especially important as motivation for the way your solution program

    will be structured.

    Kernighan and Ritchie, section 4.11.3; chapter 6 except sections 6.8 ("Unions") and 6.9 ("Bit-fields"); the entry for fopenin Appendix B.

    The sections "Abstract data types in C" and "Basic compilation control usingmake" later in thisdocument.

    Related quizzes

    Structures

    Programming assignment 4

    The "Animal" game, revisited

    Goals

    This assignment illustrates how to implement an abstract data typein C; it also gives you

  • 5/22/2018 BasicDataStructures StudyGuide

    21/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    practice with structures and linked structures, and with eliminating memory leaks.

    Problem

    Write and test two modulesto represent and process the animal data tree. One module will representthe tree in conventional C fashion as an array of character pointers, declared as follows:

    struct treeStruct { char *nodes[MAXNUMQS];

    };

    struct positionStruct {

    int nodeIndex;

    };

    The other will represent it as an explicitly linked tree, declared as follows.

    struct treeStruct {

    char *string;

    struct treeStruct *left, *right;

    };

    struct positionStruct {

    struct treeStruct* node;

    };

    In either case, TreeTypeand PositionTypewould be defined as described in House section 15.2:

    typedef struct treeStruct *TreeType;

    typedef struct positionStruct *PositionType;

    Each module will be used with the code in Appendix 1 (essentially the code you were given in

    assignment 3) to complete a program to play the animalgame.

    You are not to change the main program. Instead, you are to create three files to accompany it:animal.h, animal1.c, and animal2.c.

    animal.hwill contain prototypes (function headers) for the twelve functions that complete theprogram and typedefs for TreeTypeand PositionType. It will not contain definitions forstruct treeStructand struct positionStruct, since these depend on what module youare using. (ANSI C allows the definition of a pointer type without the immediate definition ofthe type pointed to. See the explanation of "incomplete type" in chapter 15 of House andsection A8.3 of Kernighan and Ritchie.) Finally, it will contain an #ifndefsurrounding thelines just described, that prevents compiler errors involving multiple definitions.animal1.cwill contain code for the twelve functions and the definitions for the structures forone of the implementations. The line #include "animal.h"will appear in the file before thefunctions and structdefinitions.animal2.cwill contain code for the twelve functions and the definitions for the structures forthe other implementation. It will also contain the line #include "animal.h" before itsfunctions and struct definitions.

    In addition, at least one of your two implementations should initialize the tree from a file whose

  • 5/22/2018 BasicDataStructures StudyGuide

    22/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    name is specified as a command line argument. Your program should check the result of the fopenfunction to ensure that a legal file name was specified. When your program exits, it should save thenew tree to that file, after again checking to make sure the file is writable. (Chapter 10 of House andAppendix B of Kernighan and Ritchie describes functions that will allow you to make a backup ofthe tree file before you write your new file, if you so desire). When you bring your program to begraded, accompany it by documentation of the file format.

    Any storage requested usingmallocor callocand not required for the representation of the animaldata tree should be freed using the freefunction. Tutors will require you to verify that each use of

    mallocor callocother than those whose storage is a component of the animal tree is accompaniedby a call to free.

    As in programming assignment 3, test each module on guesses that exercise "yes" branches as wellas "no" branches, and on games that result in successful guesses as well as unsuccessful guesses.Provide evidence that your functions work correctly in isolation as well as in combination.

    Miscellaneous information

    The main program's source file p4.cis online in the directory ~cs9c/libfor your reference.

    A key requirement of this assignment is the interchangeability of the modules. The tradeoff for thisdesign feature is more complex code: the array implementation forces an extra level of indirection toaccess a node, and redundant information is passed through parameters in the explicitly linked treeimplementation. (Some compilers will generate warnings about the redundancy.) The extracomplexity, we hope, will not be excessive, and will provide you with more experience workingwith C pointers.

    If you're using a UNIX account for this class, we suggest that you use themakeprogram to compileand load your completed program. Do this by creating a file calledmakefilewe've supplied such

    a file in ~cs9c/lib/p4.makefileand by typing the commandmake -e animal1ormake -e animal2depending on which of your modules you wish to test. The document "BasicCompilation Control with Make" in this document describes themakeprogram; the ambitious amongyou may wish to change the "make file" to automate your testing as well as your compiling andloading. The -eoption formakegives the LIBvariable in the "make file" the value of the LIBvariable from the environment.

    The following recursive algorithm may be used to initialize an explicitly linked tree from a file:

    read a line;if there was no line to read (the end of the file has been reached) return NULL;if the line is empty return NULL;otherwise allocate a tree node; call the algorithm recursively to get a pointer to its left child; if the left child isn't NULL call the algorithm recursively to get a pointer to the right child; return a pointer to the tree node.

  • 5/22/2018 BasicDataStructures StudyGuide

    23/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    Checklist

    A satisfactory grade on this assignment requires the following:

    Correct behavior in guessing and adding nodes to the animal tree.Freeing of memory not used in representation of the animal tree.Sufficient test games.

    File input in at least one implementation, using an error-checked file name supplied on the commandline, with accompanying documentation of the file format.File output in at least one implementation, using a file name supplied on the command line (creatinga backup of the file before writing is optional).Correct setup of .hand .cfiles.Good style and layout.No function more than 24 lines long.Reasonable names for functions, variables, and parameters.Appropriate use of auxiliary functions.Evidence that subprograms were tested in isolation.No changes to main program.

    MJC, DE: 8/99

    Appendix 1: Main program for animal

    /* DO NOT MODIFY THIS FILE */

    #define FALSE 0

    #define TRUE !FALSE

    #define MAXSTR 80

    #include

    #include "animal.h"

    /*

    * Play the "animal" game, in which the program attempts to guess an animal

    * that the user is thinking of by asking yes or no questions. Eventually,

    * the program either will guess the user's animal or run out of questions

    * to ask. In the latter case, the program will ask the user to provide a

    * yes-or-no question that would distinguish between the user's animal and

    * the program's best guess.

    * The data structure of questions and guesses is essentially a binary tree,

    * with each internal node having a "yes" branch and a "no" branch. Leaves

    * of the tree represent animals to be guessed by the program. If the program

    * fails to guess the user's animal, it replaces one of the leaves of the tree

    * by a node containing the new question, whose children are the program's* best guess and the animal provided by the user.

    * The structure of the program is simple. It initializes the question/guess

    * data structure, then plays games as long as the user is interested. In each

    * game, the program starts at the top of the tree (the root) and progresses

    * toward the bottom (the leaves) depending on the user's responses. Once it

    * reaches a leaf, it either has won or lost, and handles the situation as

    * described above.

    */

    int main (int argc, char *argv[]) {

    char *treefile = NULL;

  • 5/22/2018 BasicDataStructures StudyGuide

    24/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    TreeType tree;

    PositionType pos;

    char *newQuestion, *newAnswer;

    if (argc > 1) {

    treefile = argv[1];

    }

    tree = InitTree (treefile);

    printf("%s", "Think of an animal. I will try to guess what is.\n"

    "Please answer my questions with yes or no

    while (TRUE) { pos = Top (tree);

    while (!IsLeaf (tree, pos)) {

    pos = Answer (Question (tree, pos))?

    YesNode (tree, pos): NoNode (tree, pos);

    }

    if (Answer (Guess (tree, pos))) {

    printf ("I got it right!\n");

    } else {

    GetNewInfo (tree, pos, &newAnswer, &newQuestion);

    ReplaceNode (tree, pos, newAnswer, newQuestion);

    }

    if (!Answer ("Want to play again? ")) {

    WriteTree(tree, treefile); return 0;

    }

    }

    }

    Appendix 2: Functions to be implemented in each module

    WriteTreeis a new function you have to write.

    /*

    * Writes a tree to the given file (if specified).

    */void WriteTree(TreeType tree, char *file);

    Descriptions of these functions appear in programming assignment 3.

    /*

    * Return an animal tree (from file, if specified).

    */

    TreeType InitTree (char *file);

    void PrintTree (TreeType tree);

    PositionType Top (TreeType tree);

    boolean IsLeaf (TreeType tree, PositionType pos);

    boolean Answer (char *question);

    char *Question (TreeType tree, PositionType pos);

    char *Guess (TreeType tree, PositionType pos);

    PositionType YesNode (TreeType tree, PositionType pos);

    PositionType NoNode (TreeType tree, PositionType pos);

    void ReplaceNode (TreeType tree, PositionType pos, char *newA, char *newQ);

    void GetNewInfo (TreeType tree, PositionType pos, char **newA, char **newQ);

  • 5/22/2018 BasicDataStructures StudyGuide

    25/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

  • 5/22/2018 BasicDataStructures StudyGuide

    26/51

    1/9/1Quiz-Arrays, structures, and files

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.arrays.structs.files.html

    Quiz Arrays, structures, and

    files

    This quiz covers typical uses of C arrays (one- and two-dimensional), structures, and files.Included are questions on the typedefdeclaration and on the predefined file pointers stdin,

    stdout, and stderr.

    Readings

    House, chapters 9 through 11.

    Kernighan and Ritchie, material on arrays in chapters 1 through 4, section 5.7, 6.1 through 6.3,6.7, and 7.1 through 7.7.

    Suggested exercises

    House, section 5.7 #2 and #7; all "short answer" self-test exercises and test questions in chapters9 through 11.

    Sample quiz

    1. Fill in the blanks in the program below so it prints the contents of the file whose name isprovided by the user.

    #include int main ( ) {

    char fileName[32]; char c; FILE *inFile; printf ("File name? "); gets (fileName); _________________________ ; if ( ____________________ ) { fprintf ( _____________ , "File doesn't exist!\n"); exit (1); }; while ( ____________________ ) { /* get a char if not done fprintf ( _______________ ); /* print it */

    } return 0; }

    2. Define a structto represent dates. The structmembers should be a string representingthe month, an integer representing the date in the month, and another integer representingthe year. Then define the type Dateto be synonymous with the structdefinition, anddefine an array dateListof five dates.

    3. Fill in the blank in the code below so that it moves each element of the valuesarray to the

  • 5/22/2018 BasicDataStructures StudyGuide

    27/51

    1/9/1Quiz-Arrays, structures, and files

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.arrays.structs.files.html

    immediately subsequent position in the array. The loop should discard the last value in thearray. Thus if the array contained the values 1, 2, 3, 4, and 5 before the loop, it shouldcontain the values 1, 1, 2, 3, and 4 after the loop.

    int values[5]; ... for ( ____________________ ) { values[k] = values[k-1];

    }

    4. Modify the definition of the valuesarray in exercise 3 so that it also initializes the array tocontain the values 1, 2, 3, 4, 5.

    5. Write a function HasZeroDiagonalthat, given a 5-by-5 integer array, returns 1 if all theelements on the main array diagonal are zero and returns 0 otherwise.

  • 5/22/2018 BasicDataStructures StudyGuide

    28/51

    1/9/1Quiz-General use of pointers

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.general.use.ptrs.html

    Quiz General use of pointers

    This quiz tests your understanding of the definition and use of C pointers. Questions for this quizask about the meaning of the *, &, and ** prefix operators; about the relation between pointerand array use; about the distinction between pointer and thing-pointed-to; and about thedeclaration of pointer arrays. You will also be expected to be able to draw a diagram of a Cpointer object, and to determine the proper declaration for an object shown in a diagram. Youshould be able to detect type clashes that would probably lead to obscure bugs at run time.Finally, you should be aware of how to use themallocand callocfunctions and of when they'renecessary.

    Readings

    House, section 6.5, chapter 9, sections 12.1-12.3, 13.1, 13.3, and appendix D13.

    Kernighan and Ritchie, sections 5.1 through 5.5, 7.8, and B3.

    Suggested exercises

    House, section 12.6 #2 and #3; section 12.7 #3; section 13.7 #1-4 and #6; section 13.8 #1-3. Youwill also be expected to write short program segments.

    Sample quiz

    1. (Exercise 5.3 in K&R) Rewrite the strcatfunction given below, which uses arrayindexing, to use pointers instead.

    void strcat (char s[], char t[]) {

    int i, j;

    i = j = 0;

    while (s[i] != '\0') {

    i++;

    }

    while ((s[i++] = t[j++]) != '\0') {

    }

    }

    2. Consider the following function, intended to return a string typed by the user to the caller.

    char* WordInput ( ) {

    char word[20];

    printf ("Type a word: ");

    scanf ("%s", word);

    return word;

    }

    What's wrong with the function? Does replacing its second line by

  • 5/22/2018 BasicDataStructures StudyGuide

    29/51

    1/9/1Quiz-General use of pointers

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.general.use.ptrs.html

    char* word;

    fix the problem?

    3. What is the meaning of the following declaration?

    char* a, b;

    4. Which of the following would cause compile-time or run-time problems? Please explain.Also give the type of the right-hand side of each assignment statement, and draw adiagram for each legal assignment to the pointer variable px.

    float x, *px, a[5];

    x = *px; /* 1 */

    *px = x; /* 2 */

    px = &x; /* 3 */

    &x = px; /* 4 */

    &(x+1) = x; /* 5 */

    &(x)+1 = x; /* 6 */

    *(&(x+1)) = x; /* 7 */

    *(&(x)+1) = x; /* 8 */ x = a; /* 9 */

    x = a[0]; /* 10 */

    x = *(a[1]); /* 11 */

    x = (*a)[2]; /* 12 */

    x = a[3+1]; /* 13 */

    x = a[3]+1; /* 14 */

    x = &((a[3])+1); /* 15 */

    x = &(a[3])+1; /* 16 */

    x = *(&(a[3])+1); /* 17 */

    px = a; /* 18 */

    px = a[0]; /* 19 */

    px = &(a[4]); /* 20 */

  • 5/22/2018 BasicDataStructures StudyGuide

    30/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    Program Abstract data types

    with trees

    Most of the significant breakthroughs in computing science have been achieved through a process of

    representation, that is to say, changing one's way of perceiving a problem so that it can be solved

    more easily. Structures such as lists, trees, tables and so forth have meaning to us as problemsolvers, but do not have direct existencein the computer. The C structand typedeflanguageconstructs allow programmers to represent more abstract structures in terms of the simple dataobjects built into the language.

    C allows the use of the programmer to isolate the details of the implementation of a data type in asingle file or group of files. By using access functions and header files it is possible for one series offunctions to use a data structure without ever dealing with the actual language primitives that definethe data structure. This use of an abstract data typeis good software engineering; it allows one toimplement and modify the implementation of the data structure with minimal change to the rest ofthe program.

    Careless C programmers often write code with "memory leaks", that is, instances where storage isrequested viamallocand never freed. A process that runs a long time with a memory leak, forexample, a part of the operating system or a process that runs in the background monitoring userinteraction, will eventually leave no room for other programs. This assignment gives you somepractice tracking down these problems.

    Readings

    House, chapters 10, 11, 14, and 15; sections 12.4, 13.2, and 13.3. (It will also be useful to reviewsection 13.1.) Chapter 15 is especially important as motivation for the way your solution program

    will be structured.

    Kernighan and Ritchie, section 4.11.3; chapter 6 except sections 6.8 ("Unions") and 6.9 ("Bit-fields"); the entry for fopenin Appendix B.

    The sections "Abstract data types in C" and "Basic compilation control usingmake" later in thisdocument.

    Related quizzes

    Structures

    Programming assignment 4

    The "Animal" game, revisited

    Goals

    This assignment illustrates how to implement an abstract data typein C; it also gives you

  • 5/22/2018 BasicDataStructures StudyGuide

    31/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    practice with structures and linked structures, and with eliminating memory leaks.

    Problem

    Write and test two modulesto represent and process the animal data tree. One module will representthe tree in conventional C fashion as an array of character pointers, declared as follows:

    struct treeStruct { char *nodes[MAXNUMQS];

    };

    struct positionStruct {

    int nodeIndex;

    };

    The other will represent it as an explicitly linked tree, declared as follows.

    struct treeStruct {

    char *string;

    struct treeStruct *left, *right;

    };

    struct positionStruct {

    struct treeStruct* node;

    };

    In either case, TreeTypeand PositionTypewould be defined as described in House section 15.2:

    typedef struct treeStruct *TreeType;

    typedef struct positionStruct *PositionType;

    Each module will be used with the code in Appendix 1 (essentially the code you were given in

    assignment 3) to complete a program to play the animalgame.

    You are not to change the main program. Instead, you are to create three files to accompany it:animal.h, animal1.c, and animal2.c.

    animal.hwill contain prototypes (function headers) for the twelve functions that complete theprogram and typedefs for TreeTypeand PositionType. It will not contain definitions forstruct treeStructand struct positionStruct, since these depend on what module youare using. (ANSI C allows the definition of a pointer type without the immediate definition ofthe type pointed to. See the explanation of "incomplete type" in chapter 15 of House andsection A8.3 of Kernighan and Ritchie.) Finally, it will contain an #ifndefsurrounding thelines just described, that prevents compiler errors involving multiple definitions.animal1.cwill contain code for the twelve functions and the definitions for the structures forone of the implementations. The line #include "animal.h"will appear in the file before thefunctions and structdefinitions.animal2.cwill contain code for the twelve functions and the definitions for the structures forthe other implementation. It will also contain the line #include "animal.h" before itsfunctions and struct definitions.

    In addition, at least one of your two implementations should initialize the tree from a file whose

  • 5/22/2018 BasicDataStructures StudyGuide

    32/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    name is specified as a command line argument. Your program should check the result of the fopenfunction to ensure that a legal file name was specified. When your program exits, it should save thenew tree to that file, after again checking to make sure the file is writable. (Chapter 10 of House andAppendix B of Kernighan and Ritchie describes functions that will allow you to make a backup ofthe tree file before you write your new file, if you so desire). When you bring your program to begraded, accompany it by documentation of the file format.

    Any storage requested usingmallocor callocand not required for the representation of the animaldata tree should be freed using the freefunction. Tutors will require you to verify that each use of

    mallocor callocother than those whose storage is a component of the animal tree is accompaniedby a call to free.

    As in programming assignment 3, test each module on guesses that exercise "yes" branches as wellas "no" branches, and on games that result in successful guesses as well as unsuccessful guesses.Provide evidence that your functions work correctly in isolation as well as in combination.

    Miscellaneous information

    The main program's source file p4.cis online in the directory ~cs9c/libfor your reference.

    A key requirement of this assignment is the interchangeability of the modules. The tradeoff for thisdesign feature is more complex code: the array implementation forces an extra level of indirection toaccess a node, and redundant information is passed through parameters in the explicitly linked treeimplementation. (Some compilers will generate warnings about the redundancy.) The extracomplexity, we hope, will not be excessive, and will provide you with more experience workingwith C pointers.

    If you're using a UNIX account for this class, we suggest that you use themakeprogram to compileand load your completed program. Do this by creating a file calledmakefilewe've supplied such

    a file in ~cs9c/lib/p4.makefileand by typing the commandmake -e animal1ormake -e animal2depending on which of your modules you wish to test. The document "BasicCompilation Control with Make" in this document describes themakeprogram; the ambitious amongyou may wish to change the "make file" to automate your testing as well as your compiling andloading. The -eoption formakegives the LIBvariable in the "make file" the value of the LIBvariable from the environment.

    The following recursive algorithm may be used to initialize an explicitly linked tree from a file:

    read a line;if there was no line to read (the end of the file has been reached) return NULL;if the line is empty return NULL;otherwise allocate a tree node; call the algorithm recursively to get a pointer to its left child; if the left child isn't NULL call the algorithm recursively to get a pointer to the right child; return a pointer to the tree node.

  • 5/22/2018 BasicDataStructures StudyGuide

    33/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    Checklist

    A satisfactory grade on this assignment requires the following:

    Correct behavior in guessing and adding nodes to the animal tree.Freeing of memory not used in representation of the animal tree.Sufficient test games.

    File input in at least one implementation, using an error-checked file name supplied on the commandline, with accompanying documentation of the file format.File output in at least one implementation, using a file name supplied on the command line (creatinga backup of the file before writing is optional).Correct setup of .hand .cfiles.Good style and layout.No function more than 24 lines long.Reasonable names for functions, variables, and parameters.Appropriate use of auxiliary functions.Evidence that subprograms were tested in isolation.No changes to main program.

    MJC, DE: 8/99

    Appendix 1: Main program for animal

    /* DO NOT MODIFY THIS FILE */

    #define FALSE 0

    #define TRUE !FALSE

    #define MAXSTR 80

    #include

    #include "animal.h"

    /*

    * Play the "animal" game, in which the program attempts to guess an animal

    * that the user is thinking of by asking yes or no questions. Eventually,

    * the program either will guess the user's animal or run out of questions

    * to ask. In the latter case, the program will ask the user to provide a

    * yes-or-no question that would distinguish between the user's animal and

    * the program's best guess.

    * The data structure of questions and guesses is essentially a binary tree,

    * with each internal node having a "yes" branch and a "no" branch. Leaves

    * of the tree represent animals to be guessed by the program. If the program

    * fails to guess the user's animal, it replaces one of the leaves of the tree

    * by a node containing the new question, whose children are the program's* best guess and the animal provided by the user.

    * The structure of the program is simple. It initializes the question/guess

    * data structure, then plays games as long as the user is interested. In each

    * game, the program starts at the top of the tree (the root) and progresses

    * toward the bottom (the leaves) depending on the user's responses. Once it

    * reaches a leaf, it either has won or lost, and handles the situation as

    * described above.

    */

    int main (int argc, char *argv[]) {

    char *treefile = NULL;

  • 5/22/2018 BasicDataStructures StudyGuide

    34/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

    TreeType tree;

    PositionType pos;

    char *newQuestion, *newAnswer;

    if (argc > 1) {

    treefile = argv[1];

    }

    tree = InitTree (treefile);

    printf("%s", "Think of an animal. I will try to guess what is.\n"

    "Please answer my questions with yes or no

    while (TRUE) { pos = Top (tree);

    while (!IsLeaf (tree, pos)) {

    pos = Answer (Question (tree, pos))?

    YesNode (tree, pos): NoNode (tree, pos);

    }

    if (Answer (Guess (tree, pos))) {

    printf ("I got it right!\n");

    } else {

    GetNewInfo (tree, pos, &newAnswer, &newQuestion);

    ReplaceNode (tree, pos, newAnswer, newQuestion);

    }

    if (!Answer ("Want to play again? ")) {

    WriteTree(tree, treefile); return 0;

    }

    }

    }

    Appendix 2: Functions to be implemented in each module

    WriteTreeis a new function you have to write.

    /*

    * Writes a tree to the given file (if specified).

    */void WriteTree(TreeType tree, char *file);

    Descriptions of these functions appear in programming assignment 3.

    /*

    * Return an animal tree (from file, if specified).

    */

    TreeType InitTree (char *file);

    void PrintTree (TreeType tree);

    PositionType Top (TreeType tree);

    boolean IsLeaf (TreeType tree, PositionType pos);

    boolean Answer (char *question);

    char *Question (TreeType tree, PositionType pos);

    char *Guess (TreeType tree, PositionType pos);

    PositionType YesNode (TreeType tree, PositionType pos);

    PositionType NoNode (TreeType tree, PositionType pos);

    void ReplaceNode (TreeType tree, PositionType pos, char *newA, char *newQ);

    void GetNewInfo (TreeType tree, PositionType pos, char **newA, char **newQ);

  • 5/22/2018 BasicDataStructures StudyGuide

    35/51

    1/9/1Program-Abstract data types with trees

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/p.ADTs.with.trees.html

  • 5/22/2018 BasicDataStructures StudyGuide

    36/51

    1/9/1Quiz-Linked structures

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.linked.structs.html

    Quiz Linked structures

    This quiz tests your understanding of how linked structures are created and used. It also includesquestions on more advanced uses of pointers. Finally, you are expected to know about argvandargc, which store information from the command line

    Readings

    House, sections 12.4 and 13.2-13.5.

    Kernighan and Ritchie, 5.6, 5.8 through 5.12, 6.4, and 6.5.

    Suggested exercises

    House, "short answer" self-test exercises and test questions in chapters 12 and 13.

    Sample quiz

    1. What's the difference between the use of "." and the use of "->" in referring to a field of astructure?

    2. Declare a type named ListPtrTypethat's a pointer to a struct, each instance of whichcontains an integer infomember and a nextmember that's a pointer to an instance of thestructtype.

    3. Write a function that returns a pointer to a newly-created node of the structure type youjust declared. Use sizeofand callocto allocate the space for the new node.

    4. Given the following declarations

    struct tnode {

    char *word;

    struct tnode *left, *right;

    };

    typedef struct tnode TREENODE, *TREEPTR;

    TREEPTR tree;

    TREENODE node;

    indicate which of the following are legal expressions; for legal expressions,also indicate the type of the expression.

    a. node->word[2]b. node.word[2]c. tree->left->wordd. *(tree->left)e. *tree->leftf. tree->*left

    5. What does *p++mean?

  • 5/22/2018 BasicDataStructures StudyGuide

    37/51

    1/9/1Quiz-Linked structures

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/q.linked.structs.html

    6. Page 115 of K&R contains the following program to print the argument list.

    int main (int argc, char *argv[]) {

    while (--argc > 0) {

    printf ("%s%s", *++argv, (argc > 1) ? " " : "");

    }

    printf ("\n");

    return 0;

    }

    Modify this program to print the arguments on separate lines, and to omit duplicatearguments from the argument list. If, for instance, the program is run with thecommand line

    a.out a b a c

    the output should be

    a

    b

    c

  • 5/22/2018 BasicDataStructures StudyGuide

    38/51

    1/9/1C Style Examples

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/C.style.examples.html

    C Style Examples

    by P.N. Hilfinger

    /* TITLES GO HERE *//* Comments on variables may go here */int x; /* or here */

    /* Format 1: Comments describing a function that go before it may be *//* formatted like this. This same format works for variables and general *//* commentary about an entire program or section of a program. */

    /* Format 2: Here is another possible format for extended comments at the front of a source file or before function or variable declarations. *//*** Format 3: Here is still another possible format. Some find that comments

    ** stand out better in this format than in formats 1 or 2.** Also it is possible to access all the comments via the grep command;** format 1 allows this too, while format 2 doesn't.*/int F (double a[ ], double b[ ], double c[ ], int n) /* Comments describing a function that go after its header */ /* are indented like this. */{ if (n < 0) { fprintf (stderr, "Erroneous input to F: %d.\n", n); exit (1); } else if (n == 0) { /* note that single statements */ return 0; /* should be bracketed too for safety */

    } else { int i; for (i=0; i

  • 5/22/2018 BasicDataStructures StudyGuide

    39/51

    1/9/1Abstract data types in C

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/ADTs.in.C.html

    Abstract data types in C

    What's an abstract data type?

    You're well acquainted with data types by now, like integers, arrays, and so on. To access the

    data, you've used operations defined in the programming language for the data type, for instanceby accessing array elements by using the square bracket notation, or by accessing scalar valuesmerely by using the name of the corresponding variables.

    This approach doesn't always work on large programs in the real world, because these programsevolveas a result of new requirements or constraints. A modification to a program commonlyrequires a change in one or more of its data structures. For instance, a new field might be addedto a personnel record to keep track of more information about each individual; an array might bereplaced by a linked structure to improve the program's efficiency; or a bit field might bechanged in the process of moving the program to another computer. You don't want such achange to require rewriting every procedure that uses the changed structure. Thus, it is useful to

    separatethe use of a data structure from the details of its implementation. This is the principleunderlying the use of abstract data types.

    Here are some examples.

    stack: operations are "push an item onto the stack", "pop an item from the stack", "ask ifthe stack is empty"; implementation may be as array or linked list or whatever.queue: operations are "add to the end of the queue", "delete from the beginning of thequeue", "ask if the queue is empty"; implementation may be as array or linked list or heap.search structure: operations are "insert an item", "ask if an item is in the structure", and"delete an item"; implementation may be as array, linked list, tree, hash table, ...

    There are two views of an abstract data type in a procedural language like C. One is the view thatthe rest of the program needs to see: the names of the routines for operations on the datastructure, and of the instances of that data type. The other is the view of how the data type and itsoperations are implemented. C makes it relatively simple to hide the implementation view fromthe rest of the program.

    Implementation of abstract data types in C

    In C, a complex data type is typically represented by a pointer to the information stored in the

    data type. A C function can pass the pointer to other functions without knowing the details ofwhat the pointer points to. One may also use parts of a program that have been separatelycompiled. All that a part of a program need know about functions it calls is their names and thetypes they return.

    Thus, the convention in C is to prepare two files to implement an abstract data type. One (whosename ends in ".c") provides the implementation view; it contains the complete declaration for thedata type, along with the code that implements its associated operations. The other (whose name

  • 5/22/2018 BasicDataStructures StudyGuide

    40/51

    1/9/1Abstract data types in C

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/ADTs.in.C.html

    ends in ".h") provides the abstract view; it contains short declarations for functions, pointertypes, and globally accessible data.

    The abstract data type "stack" might then be represented as follows:

    stack.h

    typedef struct StackStructType *StackType;

    /* Return a pointer to an empty stack. */

    extern StackType InitStack ( );

    /* Push value onto the stack, returning success flag. */

    extern boolean Push (int k);

    /* Pop value from the stack, returning success flag. */

    extern boolean Pop ( );

    /* Print the elements of the stack. */

    extern PrintStack (StackType stack);

    stack.c

    #include "stack.h"

    #define STACKSIZE 5

    struct StackStructType { /* stack is implemented as */

    int stackItems [STACKSIZE]; /* an array of items */

    int nItems; /* plus how many there are */

    };

    typedef struct StackStructType *StackType;

    /*

    ** Return a pointer to an empty stack.

    */

    StackType InitStack ( ) {

    char *calloc( );

    StackType stack;

    stack = (StackType) calloc (1, sizeof (struct StackStructType));

    stack->nItems = 0;

    return (stack);

    }

    ...

    Parts of the program that need to use stacks would then contain a line

    #include "stack.h"

    (Often the ".c" file also includes the corresponding ".h" file, as shown above, to insureconsistency of function and type declarations.) The program would call InitStackto set up astack, receiving in return a pointer of type StackType; it would access the stack by passing thispointer to Push, Pop, etc. Such a program would work no matter what the contents of stack.c,provided only that the implemented functions performed as specified in stack.h.

    One more subtlety: It occasionally happens that a module #includes more than one .hfile, andthe second .hfile also #includes the first. This produces compiler complaints about definitions

  • 5/22/2018 BasicDataStructures StudyGuide

    41/51

    1/9/1Abstract data types in C

    Phttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/ADTs.in.C.html

    occurring more than once. The way to avoid these complaints is to use C's conditional compilingfacility (described in K&R section 4.11.3) to make sure definitions only appear once to thecompiler. Here is an example of its use with the stack code above.

    #ifndef STACK /* any suggestive variable name is fine */

    #define STACK /* define it if it's not already defined */

    typedef struct StackStructType *StackType;

    /* Return a pointer to an empty stack. */

    extern StackType InitStack ( ); /* Push value onto the stack, returning success flag. */

    extern boolean Push (int k);

    /* Pop value from the stack, returning success flag. */

    extern boolean Pop ( );

    /* Print the elements of the stack. */

    extern PrintStack (StackType stack);

    #endif

    The first time the stack.hfile is encountered, the STACKvariable won't (shouldn't) have beendefined, so the body of the #ifndefis compiled. Since the body provides a definition of STACK,subsequent inclusions of stack.hwill bypass the body, thereby avoiding multiple definitions of

    InitStack, Push, Pop, and PrintStack.

  • 5/22/2018 BasicDataStructures StudyGuide

    42/51

    1/9/1Solutions to sample quiz questions

    Pahttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/sample.quiz.solns.html

    Solutions to sample quiz questions

    Solutions to questions for "Fundamentals" quiz

    1. Suppose that an integer variable ncontains the value 80. Fill in the blanks in the printf

    statement below so that it produces the output

    80% usually means "excellent"

    printfstatement:

    printf (" _____ ", n);

    Solution: "%d%% usually\nmeans \"excellent\". The % must be quoted with another %, not abackslash.

    2. Consider the program segment

    int k; k = getchar ( ); printf ("%d", k);

    What gets printed if the user types a 2, then hits return?

    Solution: Not a 2, but the decimal value of the ASCII character '2'.

    3. The following program is intended to compute 5! = 120, but it prints 24 instead. What's wrongwith it?

    int main ( ) { int theNum, total; total = 1; theNum = 5; while (theNum > 1) { total *= --theNum; } printf ("%d", total); return 0; }

    Solution: The decrement --should follow theNum, not precede it.

    4. What would be the effect of substituting !(theNum = 1)for thewhilecondition theNum > 1in the main program of exercise 3?

    Solution: The expression theNum = 1is an assignment, not a comparison. Its value is the valueassigned, namely 1. The value of ! 1is false, since 1 is a true value. When awhileloop's conditionevaluates to false, the loop is exited; thus the loop is never executed, and the value 1 is printed.

    5. Fill in the blanks in the code below to convert thewhileloop in exercise 3 to an equivalent

  • 5/22/2018 BasicDataStructures StudyGuide

    43/51

    1/9/1Solutions to sample quiz questions

    Pahttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/sample.quiz.solns.html

    forloop.

    int main ( ) { int theNum, total; total = 1; for ( ____ ; _____ ; _____ ) { total *= theNum; } printf ("%d", total); return 0; }

    Solution: for (theNum=5; theNum>1; --theNum) {

    6. Write down the values for all variables appearing in each statement.

    int main ( ) { int x, y, z; float a, b; x = 3; y = 5.3; z = 2; x ____ y ____ z ____ a = 2.5; b = 3.14; a ____ b ____

    /*1*/ x += y + a * z-b; x ____ /*2*/ a = b / (x%y + z) a ____ z += (x == y); z ____ /*3*/ x == (a = b); x ____ return 0; }

    Solution

    x = 3; y = 5.3; z = 2; x=3 y=5 z=2 a = 2.5; b = 3.14; a=2.50 b=3.14 /*1*/ x += y + a * z-b; x=9 /*2*/ a = b / (x%y + z) a=0.523333 z += (x == y); z=2 /*3*/ x == (a = b); x=9

    Where do you need parentheses to have xassigned a value of 14 in the statementlabeled /*1*/? What then is the new value of ain the statement labeled /*2*/? What isthe new value of xin the statement labeled /*3*/?

    Solution: Parentheses should go around the y+a. There is no change to ain the statement labeled/*2*/, and xretains the value 14 in the statement labeled /*3*/.

    7. Predict the output of the following program. Hint: only three lines get printed. (This issomewhat more complicated than any of the actual quiz questions.)

    int main ( ) { char c; for (c='a'; c

  • 5/22/2018 BasicDataStructures StudyGuide

    44/51

    1/9/1Solutions to sample quiz questions

    Pahttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/sample.quiz.solns.html

    } printf ("*** %c\n" , c); } return 0; }

    Solution: The program prints the following:

    e

    *** e *** g

    Solutions to questions for the "Functions and argument pointers" quiz

    1. What is the output of the following program segment?

    c = 'a'; putchar (c); putchar (F(c)); putchar (c);

    Assume that the function Fhas been defined as follows:

    char F (char c) { c = 'f'; return (c); }

    Solution: The three characters "afa" get printed. The variable cin the calling code is copied into thelocal variable cin F; the assignment to cin Fthus does not affect anything in the calling code.

    2. Modify the code from exercise 1 so that, on return from the Ffunction, the variable cin thecallingcode contains the character 'f'.

    Solution: F's parameter must now be an address so that the change can affect a variable outside thefunction. Four changes are necessary:

    c = 'a'; putchar (c); putchar (F(&c)); /* first change: insert ampersand */ putchar (c); ... char F (char *c) { /* second change: insert asterisk */ *c = 'f'; /* third change: insert asterisk */ return (*c); /* fourth change: insert asterisk */ }

    3. Write a functionAllDonethat, given a string as argument, returns a true value if the string is"exit"and returns false otherwise.

    Two solutions:

    int AllDone (char s[]) { if (strcmp(s,"exit") == 0) { return 1; } else {

    int AllDone (char s[]) { return !(strcmp(s,"exit"));

  • 5/22/2018 BasicDataStructures StudyGuide

    45/51

    1/9/1Solutions to sample quiz questions

    Pahttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/sample.quiz.solns.html

    return 0; }}

    }

    4. Write a function GetWordAndValuethat prompts the user for a string and an integer andreturns both to the calling program. Assume that the caller has already provided space inmemory for all the characters of the word.

    Solution

    void GetWordAndValue (char word[], int *value) { printf ("Type a word: "); scanf ("%s", word); printf ("Type an integer: "); scanf ("%d", value); /* note that value is already a pointer */ }

    5. Write a main program that calls GetWordAndValueand echoes the values returned.

    Solution #include int main ( ) { char word[20]; int k; GetWordAndValue (word, &k); printf ("word is '%s', k is %d\n", word, k); return 0; }

    Solutions to questions for "Arrays, Structures, and Files" quiz

    1. Fill in the blanks in the program below so it prints the contents of the file whose name isprovided by the user.

    #include int main ( ) { char fileName[32]; char c; FILE *inFile; printf ("File name? "); gets (fileName); __________________ ; if ( _____________ ) {

    fprintf (stderr, "File doesn't exist!\n"); exit (1); }; while ( _______________ ) { /* get a char if not done */ fprintf ( __________ ); /* print it */ } return 0; }

    Solution: The following code goes in the blanks:

  • 5/22/2018 BasicDataStructures StudyGuide

    46/51

    1/9/1Solutions to sample quiz questions

    Pahttp://inst.eecs.berkeley.edu/~selfpace/studyguide/9C.sg/Output/sample.quiz.solns.html

    inFile = fopen (fileName, "r") ; if (inFile == NULL) { fprintf (stderr, "File doesn't exist!\n"); exit (1); }; while ((c=getc(inFile))!=EOF) { /* done? */ fprintf (stdout, "%c", c); /* print it */

    2. Define a structto represent dates. The structmembers should be a string representing the

    month, an integer representing the date in the month, and another integer representing theyear. Then define the type Dateto be synonymous with the structdefinition, and define anarray dateListof five dates.

    Solution

    struct date { char month[10]; /* September is the longest month name. */ int dateInMonth; int year; }; /* Don't forget the semicolon! */

    typedef struct date Date; Date dateList[5];

    3. Fill in the blank in the code below so that it moves each element of the valuesarray to theimmediately subsequent position in the array. The loop should discard the last value in thearray. Thus if the array contained the values 1, 2