1?1/15/98 ---------- modular fashion - [modular development] - you write the programs in STAGES. ifstream is a "data type" [like float, int, et cetera] copy of program paper data set [paper and electronically] copy of the output CIS141 - MOD 1 [Module 1] Topics Covered: - scope - persistence - variable & perimeter types - module flow - design - documentation - c++ debugging aids Study Assignments: - Review Chapter 3, 6 - Run Mod1Test at the end of the chapter Issues involving Variables and Modules: Variables: -scope for a variable name (i.e. - where is it accessable?) -what is the lifetime for a variable? [persistence] Modules: (they're functions in C++) -Mathmatical functions are restrictive > - 0 values returned (void) > - 1 value returned (mathmatical) -Design Issues -reusability -portability -maintainability [see program data stack - in notebook] format parimeter / actual parimeter : formal parimeter: f(x)=|X| actual parimeter: f(3)=3 f(-1)=1 sub procedure , function , module , subroutine - all the same thing. Types of Variables: Local Variable: -scope is for a single module [has better control over the data] Global Variable: -scope is for a program and all of its modules main function - will be a "driver" - will go and get different proceedures side effect - you can't always account for everyone's functions...you can't always tell. you usually only get back RESULTS. hole in the scope - someone assumes someone else didn't get the right result from the function. 1/16/98 scope - area of the module concerning a certain command / area. local variables take over global variables...'specially in a certain function. More on Local Varables.... How? - declare variables within the scope of the function Benefits? - allocated what an when needed for module - released upon exit of module ; allows for task accountability. Liabilities - affects the stack - more resources are needed - functions are restricted to 0 (void) or 1 (mathmatical) value returned. Example: int main () { int x,y,z; ... return (0); } Bytes: Integer [2 bytes] (X,Y,Z) Example int sum31IntsVersion1 (int in1, int in2, int int3) {int answer; answer=in1+in2+in3; return (answer); } to call: sum31IntsVersion1 (x,y,z); don't send a "float" into an "int" box...et cetera [when you sent values out to the sub-routine] MAKE SURE TYPES MATCH More on Global Varables.... How? -declare variables before the main function Benefits? -"common access" to data. -solves eficiency of notion of function in C++ Liabilities? - accountability for data changes - not reusable - not portable - side effects: -unexpected changes to a variable -hole in the scope situation [local variabled hides global variable of same name] C++ code is REENTRANT code...when you go back out to a function, it acts as if it was JUST visited for the first time. USING c141m1a1.cpp (in notes dir) Reusability? - can we block copy getABC and convert letters to x,y,z? NO - since x,y,z are local to main() ; not global. - can get cut and paste getABC into some other project? Yes, but ONLY if it too has global variables called a,b,c Portability? - can we reuse the code for other inputs? No. it is "hardwired" to a,b,c so it is not flexible. 1/20/98 ----------- Name Bytes a 2 bytes a piece b c x y z Now edit a file called REFRENCE.CPP: Observations: -in first call to get3Ints: in1,in2, and in3 are aliases for a,b,c, - respectively. -in second call to get3Ints: in1, in2. and in3 are aliases for d,e,f respectively. -the cin statement in get3Ints is actually filling the stoorage cells of the local variable from main() -get3Ints is reusable and portable since it is based on parameters rather then global variables void get3Ints (int&,int&,int&); call by REFRENCE [with &'s] data stack: f 2 bytes e d c [main] b a while function is going on: a,b,c become in1,in2,in3 while function is going on: d,e,f become in1,in2,in3 get: [you have to know these!] NUMBER ORDER TYPE trace into [when debugging] steps through main and steps through the functions step over [when debugging] goes straight through [executing the functions, but not line by line] [for program to be done] employer id's are UNDER 32000 [use int] (Set width) Parameters: ----------------- Formal Perameters: - Decide how intermodule data flow is to take place >> input only >> output only >> input and output >> other factors Actual Parameters: - how to supply the intermodule data? __________________ CALLER __________________ | | ________ CALLED ________ void get3Ints (int& in1, int& in1,int& in1) call by refrence - output only [going IN, nothing but random garbage] Ways of Parameter Passing: ----------------------------------------- Call by value int sum3 (int in1, int in2, int in3) to call: sum= sum3 (a,b,c); looks like: {int answer; answer=in1,in2,in3); return (answer); } data stack: [in notebook] Call by refrence void sum3 (int& sumOf3, int in1, int in2, int in3) [shares data space with other variables in MAIN] to call: sum3 (sum,a,b,c); Call by Constant Refrence: void sum3 (int& sumOf3, const int& in1, const int& in2, const int& in3) **use this whenever possible** Call by Value: ========== When to use: When the actual parameter must be protected and there is enough extra data space. How to use: -actual parameters: sum=sum3(a,b,c) -format parameters: int sum3 (int in1, int in2, int in3) Module Communication: -input only for a,b,c -sum is assigned the value returned by sum3 a=in1, b=in2, c=in3 [Number, Order, Type] Call by Refrence: ============= When to use: When the actual parameter can be altered directly How to use: -actual parameters: sum3(total,a,b,c) -format parameters: void sum3(int& sumOf3, int in1, int in2, int in3) Module Communication: - output only for total - input only for a,b,c example: sumOf3=in1+in2+in3, return, } Call by refrence - example 2: How to use: -actual parameters: getCheckAmount(accountBalance,checkAmount) -format parameters: void getCheckAmount (float& balance, float& check) Module Communication: - output only for check amount - InputOutput for accountBalance Call by constant refrence When to use: When the actual parameter must be protected and there is NOT enough extra data space. How to use: -actual parameters: sum3(total, first,second,third) -format parameters: void sum3(int& sumOf3, const int&in1, const int&2, const int&3) Module Communication: - output only for total amount - Input only for first, second, third **protect weights of scores when writing your functions - make them constants [not global]** once you input your values, you can constant them....which is what we're going to do. homework: write 2 functions 1- math like function to sum 3 ints [includes a return like command] 2- void function that will use call by refrence to sum 3 ints [Math] //declaration int sum3Intsv1 (int,int,int), . . //call sum=sum3Intsv1(a,b,c); . . //definition int sum3Intsv1 (int first,int second,int third), {int answer; answer=first+second+third return (answer); } [void] //declaration void sum3intsv2 (int&, const int&, const int&, const int&) **** //call sum3Intsv2(sum,a,b,c); . . . //definition void sum3intsv2 (int& total, const int& first, const int& second, const int& third) . **** . . total=first+second+third; return; } **** note: total and int& [first one] share the same space ============================================================ Taxonomy of Module: Communication Flow -Input only - call by value or const ref -Output only - single result returned: Use "math" type function in conjunction with an assignment statement. - Multiple results returned - use list of call by refrence parameters -Input/Output -Call by refrence When doing a function - include PRE-CONDITIONS and POST-CONDITIONS: [ Before] [Math Like Function] int sum3V1 (int a, int b, intc) {int total; total = a,b,c; return (total); } [Void Function] void sum3V2 (int& total, int a, int b, int c) {total=a+b+c; return } [Math Like Function] [After] int sum3V1 (int a, int b, intc) //Preconditions: three integers will be passed to the function by value. //Postconditions: returns an integer that is the sum of three integers {int total; total = a,b,c; return (total); } [Void Function] void sum3V2 (int& total, int a, int b, int c) //Preconditions: The actual parameters associated with aliases will be input to // the function. //Postconditions: The sum of the three integers will be in the alias total. {total=a+b+c; return } [if it's a constant - include changes will not be allowed] 1/23/98 ---------- When you're writing code using INPUT and OUTPUT files, you should promptly CLOSE those files at the bottom of your program: outFile << endl; } //end of while loop //display final survey results displaySurvey (employeeCount, exeCount, accCount, unaccCount); //closing files inFile.close (); outFile.close (); return (0); //0 if all went well } //end main Call by Value: Data is protected New Space is allocated Call by Refrence Data is not protected No New Space is allocated Call by Constant Refrence Data is protected No new space is allocated VOID - returns multiple variables back. (as a return) 1/26/98 - 1/27/98 - ACTIVITY 4 ================= Build a function called swap2Ints that will swap two integers -write prototype -write preConditions, PostConditions -write Data Flows -Write the function Problem Statement: ============== Problem 1: Design a program that inputs 3 integers and lists the integers in ascending order. sorts: bubble sort - compare, and if one is larger, swap it. [see page 3 of notes] for how many passes, you'll have elements-1. for how many compares?, you'll have elements * passes / 2 and for how many elements, you'll have elements. :) bubble sort FORMULAS: EXAMPLE ================== ======== x elements 6 elements x-1 passes 5 passes x (x-1) --------- 15 compares 2 also : functions can call functions. data aggragates - extra data values 1/28/98 - FUNCTIONS ================ Array - a collection of data that is the same type. homogeneous - array with data of the same type. heterogeneous - called structs Data Aggretates: [Module 2] Data types: - Primitive Data Aggregates - enum - array - struc Data Structures - User Defined Aggregates Assignments: - Read 7.2 - 7.4 [review of cis140 concepts] 7.5 - 7.6 Chapter 9 of the text (omit section 9.6) and section 10.4. then run Mod2Test. arrays by the mid-term [9.1-9.] , structures - after the midterm. Other data types: [Aggregates]: What are they: They define a group of data elements at once. Why?: We need a more efficent way of describing the data. Motivation: Three aggregate problem types. example: int x [100]; -Simple name lists - want to use list items by name - implementation of concept of boolean - makes code easier to read. -Homogeneous Collection of data [an ARRAY!] - we want to perform operations involving list of same type data Example: problem to extend Sort3Ints to 1000 integers * (500*999) =499,599 comparisons were required * Only available strategy is cloning strategy: * each comparison required a block of code; (499,500 blocks of code) * algorithm is not difficult to decscribe; program is large because space needed to repeat the code - not because of amount of data. Inplementation of concept of database * group of data of different types: A student record * want to perform operations involving record Simple lists: enum - -Permits the user to build an ordered list of named components. -The first component listed is associated with the numberal 0; the second with 1; et cetera. -Permits the use of names instead of numerals -Supports program documentation enum Months{ 0 JANUARY, 1 FEBRUARY, 2 MARCH...}; Months monthOfYear; [takes up 2 bytes] -the user is allowed to define their own data types. (c++ didnt' come up with MONTHS, but we did!) enum Boolean (FALSE, TRUE); (does not allocate space) Boolean MoreData; (allocates 2 bytes) -2 byte of storage is used for MoreData -FALSE is associated with the numeral 0 -TRUE is associated with the numeral 1 -problems associated with the boolean: 1) cannot use cin to input F or T 2) directly into moredata 3) must make assignment to moredata according to some situation Simple Lists: another enum type: enum Day (MON, TUES, WED, THURS, FRI, SAT, SUN); Day Birthday; - Not the same as storing the string "MON" - 2 byte of storage is used for a birthday - other problems: -birthday = MON+1 -birthday = MON+1 Homogeneous Data Lists: Array Definition: An Array is: -named data aggregate of: -every element / cell in the arrregate is referenced by the same name -contiguously stored: -consecutive memory locations - most cells have a successor and a predeccessor that corresponds to the memory location -homogenous componts that can be -all of the same data type -individually directly accessed via an index / subscript -the aggregate name and an integer or intere variable name is used to reference an element / cell of the collection An array will allow us to implement a list =============================================== int myArray [10] - creates 10 elements that are all integer. ** in C++, arrays start at 0. (0,1,2,3,4,5,6,7,8,9) myArray [cursor] myArray [i] ^^^----index and subscript. Homogeneous data lists: Array: int testScore [100]; - allocates a block of 20 bytes, in two byte cells of integer type - the first cell is referenced as testScore [0] - the second cell is referenced as TestScore[i]; the (i+i) cell is references as TestScore[i]; - (i+1) references the cell immediately after the (i+1) cell; - (i-1) refernces the cell immediately before the (i+1) cell. LIMITATIONS: ========== No protection from going beyond the limits of the array -- TestScore [199] does not result in a runtime error!! If there are more than 100 scores, the program would need to be modified If there are fewer than 100 scores, the programmer would have to keep track of the last cell used to process the data correctly. =========================================================== lastcell - the last cell i've actually used. myArray [cursor]> myArray [cursor+1] char Vowel [5] -- DOES allocate storage - allocated a block of 5 bytes, in one byte cells of char tyoe - to assign the letter "A", an assignment statement can be used : Vowel[0]="A"; Why is this not the same as enum Vowel [A,E,I,O,U] ? -- does NOT allocate storage. char Vowel [5]; //in the top - declaration vowel [0] = "a" vowel [1] = "b" cin >> Vowel [0]; cin >> Vowel [1]; What is involved with implementing a list in a programming language?: Data Storage: -Cells in the list - overhead storage for using the list Operations (functions in C++) -manipulation of the data in the cells - accessing the data in the cells - manipulation of the one of more lists example: for (cursor=0; cursor <= lastcell; cursor ++) 1/29/98 Implementing a list w/ an array What is involved w/ implemetning a list in a programming lang? *Data storage -cells in the list -overhead storage for using the list *Operations(functions in c++) -manipulation of the data in the cells -accessing the data in the cells -manipulation of the one or more lists *cells in the list -LIST can be static(fixed size) ,ex vowels, days of the week or dynamic(grows and shrinks) telephone #'s to remember -ARRAY is fixed size long int PhoneNUmbers[100]; -Thus the # of elements alloocated in the array must be the largest anticipated size of the list it is used for. *overhead for usage of the list: extra data may be needed to keep track of - the lastUsed cell -the current cell address, or one or more special cell addresses in the array LIST OPERATIONS *initialize(fill components of the list w/ data) ex. set of all elements of an array to a value f 0. const int maxScores = 3; float weights [maxScores] = {0.6,0.3,0.1}; *manipulate a value in a specific element. *traverse -list all cell values in the list (ex printing) n *sort reorganize the values in the list in acending (or decending)order -ascening order means that the least value is stored in cell 0, the next least in cell 1, etc. *Max, Min values in a list *Search - if the search value is stored in a cellspecifiy the cell or cells that have the value; otherwise , state that the value is not located in the list *simple numeric list : Sum, Average, Variance *Numeric list such as matrix- dot product, sum, difference Problem Scenario A computer programming class that has at most 40 students. After reading in score for a midterm exam, find the average score, the highest, and the lowest test score on the midterm, list the scores in score order, and find how many there are in each grade range - # from 90-100, 80-89, DATA STRUCTURE ANALYSIS Data storage needs: -midterm integer storage for 40 students(worse case) -integer storage for the last loaded cell(dont know how many students) -ints for the highest and lowest scores, and float for the average List operation: we build this application from the bottom up by identifying the functionality that could be used. -load the array w/ midterm scores and determine the last cell in the list -pritn the scores as they are stored -sort the scores in ascening order -compute the ave mid score -determine the highest and lowest score PSEUDOCODE *Preconditions: list of 1 or more ccells have been declared int midTermList[maxStudents]; *Postconditions:list of ints is loaded -returns cell address of last loaded if at least one in list -return cell address of -1 if list is empt step1-set Boolean for valid data to TRUE step2-set cuser to first cell step3-while(more cells and valid data) repeat step 4 through step6 step4- if sdentinel is input set Boolean for valid to False step5 prompt for and input data for the current cell 1/30/98 Breakpoint [this will put a temporary "stop" in your run routine] Watch: will monitor the values of whichever variables that are being watched. printList - (Algorithm): Preconditions: Non-Empty list and address of last cell in list Postconditions: List values are printer step 1: set cursor to first cell step 2: while (more cells with data) repreat step 3 through step 4 step 3: print data from current cell step 4: set cursor to next cell step 5: return to caller cursor=0; while (....) {cout << "......" << list [cursor]; cursor ++; } while (cursor <=lastcell) [above while statement] or....printLIST.... void printList (const int list [], const int lastCell) { // PRECONDITIONS: Non-empty list is submitted; i.e. lastCell >= 0 // POSTCONDITIONS: List valued are printed int cursor; for (cursr=0; cursor <=lastCell; cursor++) cout << "the value in cell [" << cursor << "] is << list [cursor] << endl; cout << endl; return; }// exit function 2/2/98 ===== when loading anything....we need a list, and a max cell. sortList (Algorithm) PRECONDITIONS: Non-empty list and address of last cell in list POSTCONDITIONS: List values are ordered frm smallest to largest step 1: set pass counter to 1 step 2: while (pass counter is less than the number of cells to sort) repeat step 3 through step 8 step 3: set cursor to first cell step 4: while (two more cells to compare in pass) repeat step 5 through step 7 step 5: if value in first cell is bigger then value in second step 6: swap the values in the two cells [swap2int] step 7: set cursor to next cell step 8: set pass counter up by 1 step 9: return to caller all this is done in a for loop. [like a nested loop] we WILL use a for loop: for (passCounter=1,passCounter <=lastCell;passCounter++) //step 2 { for (cursor=0,corsorlist[cursor+1] swap2Ints (list[cursor], list[cursor+1)]; //all function knows is he's getting // two numbers } //end of the inner for } //end outer for see notes 2/2/98 ** problem with this - we never compared the bottom number [and made sure it was the largest!] change inner function? or outer function? [to correct this problem] load list print the list [make sure it's right] then sort it (a, lastcellused) then print it function definition: void sortList (int list [], const int& lastcell) [you don't want to change the lastcell] 2/3/98 ===== for (passctr=1;passctr<=lastcell;passctr++) { for (cursor=0;cursor<=lastcell-passctr;cursor++) { if (list [cursor] > list [cursor+1]) swap2Ints (list [cursor], list [cursor+1], } //end innerloop } //end outer loop or - use 0 as a value instead of 1 for (cursor=0;cursor<=lastcell-passctr;cursor++) { for (cursor=0;cursor;cursor++) { if (list [cursor] > list [cursor+1]) swap2Ints (list [cursor], list [cursor+1], } //end innerloop } //end outer loop void sortList (int list [], const int& lastcell); (you don't put the ampersand because call by refrence IS the default) Now...you've got a problem. You're given a list, and the location, of the lastcell. Compute the average. 1) sum it up 2) divide by the number of cells. void averageList (const int list [], const int& lastcell, float average) int sum=0; //unless you want to accumulate to random garbage. for (cursor=0;cursor <=lastcell;cursor++) { sum=sum+list[cursor]; average=float (sum)/(lastcell+1); //lastcell+1 reserves the order or operations. //also, this lastcell+1 is because cells start at 0 2/4/98 ===== find higest number find lowest number ask yourself 2 questions....where? what? findHigest ======= void findHighest (const int list [], const int& lastcell, int& highest) {//PRECONDITIONS: Non-empty list is submitted; i.e. lastCell >=0 // POSTCONDTIONS: The highest value in the list is determined //FINDS WHERE...not the WHAT. int cursor; int currentHighest; currentHighest=0; for (cursor=1;cursor<=lastCell;cursor++) if (list[cursor]>list[currentHighest]) currentHighest=cursor; highest=list[currentHighest]; return; }// exit function findHigest ======== void findHighest (const int list [], const int& lastcell, int& highest) {//PRECONDITIONS: Non-empty list is submitted; i.e. lastCell >=0 // POSTCONDTIONS: The highest value in the list is determined //FINDS WHAT....not WHERE int cursor; int currentHighest; currentHighest=0; for (cursor=1;cursor<=lastCell;cursor++) if (list[cursor]>highest) highest=list[cursor]; return; }// exit function findLowest ======= void findLowest (const int list [], const int& lastcell, int& highest) {//PRECONDITIONS: Non-empty list is submitted; i.e. lastCell >=0 // POSTCONDTIONS: The lowest value in the list is determined //FINDS WHERE...not the WHAT. int cursor; int currentLowest; currentLowest=0; for (cursor=1;cursor<=lastCell;cursor++) if (list[cursor]=0 // POSTCONDTIONS: The lowest value in the list is determined //FINDS WHAT....not WHERE int cursor; int currentLowest; currentLowest=0; for (cursor=1;cursor<=lastCell;cursor++) if (list[cursor]= 0 // lowRange <= highRange; // POSTCONDITIONS: The number of values that fall within the states range is determined int cursor; total=0; for (cursor=0;cursor<=lastCell;cursor++) if ((list[cursor]>=lowRange) & (list[cursor]<=highRange)) total++ return; }//exit function InitailizeList void initializeList (int list[], const int& lastCell, const int& initValue) {//PRECONDITIONS: Non-empty list is submitted; i.e. lastcell>=0 // and a value to assign to each cell is given //POSTCONDITIONS: Each cell in the list is assigned to initial value int cursor; for (cursor=0;cursor <=lastcell;cursor++) list[cursor]=initValue; return; }// exit function to start an array: type listname [size]= {data,value,number,four,five} things to do with an array: load print sort average high low initialize EVERYTHING is a FOR loop traverse....hit every stop along the way (stopped in every cell) SERIAL SEARCH (can be sorted or unsorted...doesn't matter) will find the FIRST match. Will look at EVERYTHING [it's traverse] ========= void serialSearch (const int list[]. const int& lastCell, int targetvalue, int& location) {//PRECONDITIONS: lastcell >= 0 ; target is valid type //POSTCONDITIONS: location of target in list is returned or -1 int cursor; location=-1; // this is not a location in your array for (cursor=0, cursor <= lastCell; cursor++) if (list[cursor]==targetValue) location=cursor; return; section 10.4 in book talk about "big 0" notation READ IT.... BINARY SEARCH [must have a sorted list first!] Will only look at about 10 places. =================================== (after midterm) 2/16...... many many extra points for putting a sort in the structs program remember.....when you move the employee id [which you sorted by], you must move the other data as well! structs are defined globally. struct student { int id; int age; }; quiz friday...on structs. new name for a function header.....SIGNATURE. differences between data and a struct: array: data....same type homogeneous access via a subscript / index struct: different data types heterogeneous uses field names (oneStudent.id) struct Student { int id; int age; float scores[3]; }; student onestudent; stuent myClass[10]; build an offset table....(for one student) field offset oneStudent.id 0 oneStudent.age 2 oneStudent.scores[0] 4 oneStudent.scores[1] 8 oneStudent.scores[2] 12 (see notes.....2/18/98) 2 id 2 age 12 array (floats...3 of them) ----------- 16 bytes myClass [10]; 160 bytes. (16 X 10) another example: struct Date { int day; int month; int year; } field bytes ===== ==== day 2 month 4 year 6 *** a struct IS a NEW datatype seperate example...struct within a struct....running a "path": onestuent.testate.day myClass[cursor].id=10010; myClass[cursor].testDate.day=18; myClass[cursor].scores[0]=18; ~~ - array in a struct ~~ - array strings / char arrays 2/19/98 be able to COPY, LENGTH, COMPARE, and CONCATENATE (join) CIS141 - Module 3 String as array -common operators String as class -string String as array =========== string is treated as an array of characters support for common operations on string as array is obtained by using: #include an extra byte for a null erminator byte is required example: char name [31]; //for a 30 byte string null terminator "\0" -inserted automatically by common operators -in some instances, the programmer must insert a null terminator \0 for the string. String a array (Common Operations: Input / Output) -- Copy a string to another string -strcpy (destination, source); -- Compute string length -strlen(string A); -- Concatenate two strings [join two strings together] -strcat (stringA, stringB); Compare two strings -strcmp (stringA, stringB); returns 0 is equal returns negative number if stringA < stringB returns negative number if stringB < stringA 2/25/98 ===== list operations load search questions to ask yourself: 1) is the target in the list? 2) how many times is the target in the list? search: //numberic array for (cursor=0;((cursor <= lastcell) && (more)(),cursor ++) {if (list [cursor] == target) {//#1 more=true; //#2 counter++; } //character array //strength length [strlen] tells us how long the last char is for (cursor=0;((cursor <= strlen) && (more)(),cursor ++) {if (list [cursor] == target) {//#1 more=true; //#2 counter++; } initialize? ;-) sort? print loading.... we could have "white space" if we load at declaration time. cin could go after the end of the array. loop does line1 [cursor]=keystroke; basic functions: (string.h) - standard length = strlen copy = strcat concatenate = strcat compare = strcmp (cstring.h) - becoming standard cstring.h - defines a class type string. line 1.length() <- method. ~~~~~ - object *** review page 144 *** length = line 1.length() copy = line1=line2 concatenate = line1=line2+line3 compare = line1 > line2 ya don't have to assign a length to these in declaration ctype.h = "topupper" and "tolower" ;) 3/2/98 ====== FILES.... open files files() fail {notifies you when a file open fails} fail() eof - end of file eof() << >> 3/4/98 ***BINARY FILES*** playerFile.open ("c:\\temp\\player.dat",ios::out|ios::binary); //ios = input / output stream.....::out means output (default is //input file)....that's why we're doing ios:out. (in binary directory) ios::in //default ios::out ios::binary ios::ate //(at end, at the end) ..to seperate any of these items, there is ONE BAR = |, to seperate them. default is text...so now we have to tell it it is binary. while(!textFile.eof()) {// begin while // process current data contains a system input of the "end of file" ...binary files are MUCH more efficent..... text files binary files ======== ========= ascii binary "13000" takes 5 bytes "13000" takes up 5 bytes float (43076.521) 4 bytes sequential access direct access (makes it faster) ...binary files are MUCH more efficent..... just about everything takes up less space processor runs binary files anyway...text must be converted to binary to run binary files are NOT very portable. direct access is REQUIRED!! [22 bytes] [22 bytes] [22 bytes] [22 bytes] home address + size of block + size of block + size of block ftest 7 will keep up with actual write positions...compiler does not do that anymore. 3/9/98 ASCII binary ASCII test.txt ->ftest7 ->players.dat -> ftest8.cpp -> cout pulls in ->produces -> pulls in -> produces test.txt players.dat ********************************** program 4 ************************************** program 5 When you write to binary file in program 4 *****probelm reading from array****** id scores total final Grade 1) move the record of one employee to a temp record and write that guy out 2) put write in a function where you are only sending over one rec to be written 1) for( ) { write one record to a temp file ( one of the structs) then write temp record to binary file } 2) Use a function for write statement _____________________________________________________________________________ Ways to open files ____________________________________________________________________________ logical physical ifstream //ifstream infile//ifstream infile("c:\\........")] ofstream fstream //default is input for text//can be used for input or output //fstream fileName; _____________________________________________________________________________ ****************************Write on quiz or final*************************** _____________________________________________________________________________ //file demo2 do //you know you are going to ask atleast once {cout <<"Enter filename" cin >> filename; outFile.open(filename); if(outFile.fail()) { cout << "ERROR"; }while(outFile.fail()); do {cout <<"Enter filename" cin >> filename; inFile.open(filename); if(inFile.fail()) { cout << "ERROR"; }while(inFile.fail()); *************************************************************************** _____________________________________________________________________________ Reading from a file _____________________________________________________________________________ *************************************************************************** Don't have to worry about get.//another way of doing a read. 1)text file inFile>>someVar; outFile<>someVar; //intialize while(!inFile.eof()) //test { //process inFile>>someVar; //update } 2) binary file **inFile.seekg (how many blocks *sizeofblock);//position head for direct access **inFile.read((char*)& someVar, sizeof(someVar); while(!inFile.eof()) //test { //process inFile.read((char*) & someVar,sizeof(someVar); } //read binary file binFile.read((char*)& someVar,sizeof(SomeVar); //write binary file binFile.write((char*)& someVar,sizeof(SomeVar); ___________________________________________________________________________ Reasons to use text files (Good things about) ___________________________________________________________________________ 1) easy to edit,read 2) easy to print 3) hold data of different types in any order 4) easy to port //take to another computer or program all it sees is ASCII ___________________________________________________________________________ Bad things about text files ___________________________________________________________________________ 1) requires numeric data must be translated input ASCII -> internal representation //can't process ASCII the way it //is the compiler has to //transfer it to its own format output internal representation -> ASCII 2) have to have white space //some way for compiler to know where one guy //stops and the other begins. 3) can only do sequential access (only way to go through is to go all the way through). 4) text representation takes more bytes than int representation 0130000 //takes 7 bytes in binary it would only take 2 bytes __________________________________________________________________________ Good things about binary files ___________________________________________________________________________ **1) direct access** //best part about binary files 2) can do sequential access if we want to. 3) no conversions required for input of numeric data not needed // input ASCII -> internal representation not needed // output internal representation -> ASCII 4) no white space needed //data is packed tight file will be smaller 5) saves space ___________________________________________________________________________ Bad thing about binary files ___________________________________________________________________________ 1) all data are the same type // you can't put in a sent value (-1) 2) not easy to read or print // can't read it // only way to read binary is to put it back through a program 3) not easy to port // can port test.txt but not players.dat 4) can't use >> extraction operator 5) can't use << insertion operator ___________________________________________________________________________ open binary file ___________________________________________________________________________ binFile.open(filename,ios::binary|ios::in|ios::out|//read in and write out binFile.open(filename,ios::binary|ios::in //read in //use in 5th program binFile.open(filename,ios::binary|ios::in|ios::out|ios::ate read head //tellp(); must use ios::ate read write //tellg(); binFile.open(filename,ios::binary|ios::in|ios::out //use in program4 //read in and write out streampos works like an long int to get file size in bytes file size in bytes numerics = __________________ sizeof(someVar); Fill in the blank short answer definisiton functions trace program read glossary writing program: input - what it needs to look like ==process== output - what will it be data structures needed: int char float array struct ========= contreol structures: sequence, selection, loop what do i need to......... do something: sequentially decision statement or loop enum: makes code easier to read, but you can code without using enum it assigns a number to a variable - you can not do input and output with enum array is a list.....it's all of the same type of data. use cursor, predeccesor, or the successor [x, x-1, x+1] start with 0 and have 5 elements 0 1 2 3 4 be careful NOT to go past the end of the array arrays of : int char float Employee Player ========structures. :) Student structures.....different types of data operations of an array ================= load print search = binary search - things must be sorted serial search - always applicable 5000 elements with a serial search will take at most 5000 compares (worst case scanario) when dealing with an algorithym, assume worst case scanario [the main code] know how to find how many compares with a binary search 2 (n-1) is less than 5000 [representing # of elements] 5000 is less than 2(n) 2(10) = 1024 2(11) = 2048 2(12) = 4096 2(13) = 8192 2(13) is the only one more than 5000....so there's your weineer. :) 13 compares. [because 2(13) is used....remember 2 is binary] other array options: ================= sort bubble sort: dumbest dumber dumb *** look at what makes one better than the other struct: know how to figure up how many bytes are in one: int float in char[16] int int:2 float:4 int:2 char:16 int:2 matter of what comes before [look up offset] how much work does an algoritym have to do? binary search vs serial search vs sort log2n n n^2 sorts not only compare, but they have to swap strings: string.h ====== length copy conatanate compare cstring.h ======== all the goodies. :) binary files: similar to an array because you're moving same size blocks around place read and write head binfile.open(physicalfilename, ios::binary | ios:: in | ios::out | ios:ate) (object) (method) method makes link between object and filename class is like a type object is an instance of class array = there is no more room after maxcells array is like a hotel.....they are a set size ill be smaller 5) saves space _________________________________________________________________________wrniZek`\WSN^J ^|vF re m i dI `j [ W R[4N_4J _4b7w7s=o >khg,jctm_y[zWH{Su{O2|K 2|<|w=|sG|oH|kR|gS|c]|_[zWH{Su{O2|K!2:_su24Lvx!#HJr "IKgiFHZ'XZ  \^^z|35BWt " $ & ( 1 e s + B D D F c e k # 3 C T x % G G I l n | ~ E d f h v  !$'*-/13\^mo$&357EHKVYkmo "$t(*7JL` 4<PSV`hrtt 79Hnpz ?qs}/;;=(?ln6}'=j02 NPgeg  &EHKSknq HQS\twz} $-02np  k {  /!2!;!Q!S!t!!!!!!!!!!""""""&"("I""""" # ###!#P###($7$?$B$B$D$$$$$$$%%%-%/%F%H%h%%%%%%%%&&&%&8&P&R&d&{&&&&&&&''='P'P'''''''''''(($(s((((((((((( )&)()B)e)g))))))*`*i**********+F+w++++++++++,,,,,,.,<,E,n,|,,,,,--6-8-w------..3.\.|.~...$/U/// 0Y0[000001C1111112 22(2*2T2V2222233H3q333334C4E4g4i444455)5=5?5A5`5b5|55555G6q6666/7b7d7777888:8M8Z8\8888888969h999::):5::::::B;x;z;z;;;; <<W<<<<=C=E=v=x======== > >>1>Y>[>z>>>>>>>?%?2?4?6???b?b????? @5@X@@@@@@AKAAAB%BqByByB{BBBCDCpCCDcD{DDD1E7EfEEEEFKFKFFFFFF GCGGGHKHHHHHI3I5IAIIIIIJBJnJJJKOKQKZK\KKKK L LMLwLyLyLLLM'MAMCMEMPM^MuMMMMMMMMMNdNdNNNNNOO-O6OIOKOSOZOOOOO.PMPPPPP(QgQQQQQQ1R3RLRNRRRRRLSdSSSSSSSS T TPTRTTT_TTTTTTUU+U-U5U5UUkUoUUUV3VPVRVvVxVVVVW>W`W}WWWWWWWXSXUXkXmX{XXXXX-YXY^YvYxYYY ZZZZ Z4ZHZJZtZvZxZZZZ[X[w[[[[[[[\9\C\V\X\Z\f\p\\\;]V]c]x]]]]]]]^^^^d^^^__%_7_a___________?``````a8aSajasaaaaaaCb|b|bbbbcSc^cgcyc{c}ccccdjdddde e ee e"e$e8eOenepeeeeeeeeeeef!f!f^fzfff gAgggggh&h/h1hchphrhthhhhhhiiiiSiiiiiiiij j j(j*j,j,j[j]j_jjjjjjjjjjjk%k'k7k;kFkRkRkfkjklkkkkkkkkkll2lLlNlglilklrlrlzllllllllllll mm+m.m0m2mBmQmQm[mgmrmtmvmmmmmmmn0nOntnvnxnnnnnnnnnnoo&o4o6oGoToooopGp]pppppq qDqfqhqqqqqqrr5rLr|rrrrrrrrrrrsHsJsSsUsgsssssssss t tKttttttttttttuDunuuuuuuuuuu v v-v/vLvZvwvvvvvvvvwwJwJwLwswuw}wwwwwwwwxxxxx%x'xgxixixxxxxx yy$yFyHyyyyyyzzFzHzJzJzwzyzzzzz {B{D{F{H{u{{{|0|2|_||||||||}}?}v}}}}~~5~G~I~K~w~~~~~~`bmqOcɀӀXm Z\jlɂ $&*DDVnLa;=J\o҅ "2׆چ,\^s mÈ_|ɉAjŊ9[Ջ`͌0hۍݍ%74c*w֐"lё.WYʒܒޒ ')8:LNrȓϓדד2AOclnp@|~/8:bd|іQڗ*,:HWeg6FTVřǙ̙әי?AnӚ՚$,,3?HJU_tvʛ4~HJU_tvʛ4~ Arialff gAgggggh&h/h1hchphrhthhh