Computer System Concepts
Computer System Concepts CS 350
Popular in Course
Popular in ComputerScienence
This 101 page Class Notes was uploaded by Abe Jones on Saturday September 12, 2015. The Class Notes belongs to CS 350 at West Virginia University taught by Donald Adjeroh in Fall. Since its upload, it has received 10 views. For similar materials see /class/202757/cs-350-west-virginia-university in ComputerScienence at West Virginia University.
Reviews for Computer System Concepts
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/12/15
Chapter 11 File Processing Outline 1 11 Introduction 112 The Data Hierarchy 1 13 Files and Streams 114 Creating a Sequential Access File 115 Reading Data from a Sequential Access File 116 Random Access Files 117 Creating a Random Access File 118 Writing Data Randomly to a Random Access File 119 Reading Data Sequentially from a Random Access File 1 110 Example A Transaction Processing Program 144 Command Line Arguments rm Aungmsresmed l 11 Introduction Data files can be created updated and processed by C programs Files are used for permanent storage of large amounts of data Storage of data in variables and arrays is only temporary rm Aungmsresmed l 12 The Dela Hierarchy Bit smallest data item Value of 0 or 1 Byte 8 bits Used to store a character Decimal digits letters and special symbols Field group of characters conveying meaning Example your name Record group of related elds Represented by a struct or a class Example In a payroll system a record for a particular employee that contained hisher identi cation number name address etc File group of related records Example payroll le Database group of related les in Aungmsresmed 112 The Dale Hierarchy ll Tom J u F 1 1 8 Ir 5 Ju Record 1111 Fleld 01001010 Byte mu character J T 1 Bl Record key Identi es a record to facilitate the retrieval of speci c records from a le Sequential file Records typically sorted by key in Aungmsresmed I l 13 Files and Streams C views each le as a sequence of bytes Fie ends with the endaffYe marer Or le ends at a speci ed byte Stream created when a file is opened Provide communication channel between les and programs Opening a le returns a pointer to a FILE structure Example le pointers stdin standard input keyboard stdout standard output screen stderr standard error screen FILE structure Fie descriptor Index into operating system array called the open le table Fie Control Block FCB Used by the operating system to administer a file Tn Alingmsresmed 3 Files and Streams II ReadWrite functions in standard library fgetc reads one character from a file Takes a FILE pointer as an argument fgetc stdin equivalent to getcharo fputc writes one character to a file Takes a FILE pointer and a character to write as an argument fputc 39a39 stdout equivalent to putchar 39a39 fgets read a line from a le fputs write a line to a le fscanf fprintf le processing equivalents of scanf and printf Tn Alingmsresmed l 14 Creating a Sequential Access File C imposes no le structure No notion of records in a le Programmer must provide le structure Creating a File FILE myPtr creates a FILE pointer myPtr fopenquotmyFi1e datquot openmode Function fopen returns a FILE pointer to file speci ed Takes two arguments le to open and file open mode If le not opened NULL returned fprintf like printf except rst argument is a FILE pointer the le receiving data feofFILE pointer returns true if endof le indicator no more data to process is set for the speci ed le Tn Aiirigntsreserved l 14 Creating a Sequential Access File ll fcloseFILE pointer closes speci ed le Performed automatically when program ends Good practice to close files explicitly Details Programs may process no les one le or many les Each le must have an unique name and will have a different pointer All le processing must refer to the le using the pointer Mode Description w riting exists 439 A L a Annenri nnen or create a le in 39 39 A 39 r Open a le for update reading and writing w 39 update L 39 39 L exists L A L Append open or create a le for update writing is done at the end ofthe file Tn Aiirigntsreserved 1 F191 1113 1911 ozlc 2 Create a sequenclal Elle 3 ulnclude stamina Ouiiine 4 5 1n M1110 6 1 Iniiialize variables and FILE poinier 7 1n account a char name 30 1 9 double balance 1o FILE cfptr cfpcz clientslda Elle polnce H unk quot 9 po m er 1 11 a le 12 1 cfptr 0pen quotclientsldatquot NULL 13 pnncn quotnle could nor be openednquot M else 2 Inpui doia 15 pnncn quotEnter he account name and balanceAnquot 16 pnncn quotEnter nor to end inputlnquot 2 wme 10 me 17 pnncn quot2 quot fprintf 1s scan quotstfesfelfquot aaccounc name abalance 19 20 wmle lfeo scam 3CO9 9 21 fprln cfptr quotfed Yes l2 nquot 22 accounc name balance 23 pnncn quot2 39 24 scan quotstfesfelfquot aaccounc name abalance 25 26 27 c105e cfPtr 23 29 30 retum o 31 Ouiiine Enter the account name and balancel Enter nor to end 1npucl s 24 98 Program Ouipui lwaIi 000 000 2 r 1 n m o o 0 stone 42l16 500 inch 224l62 Tn All rights reserved 144 Using CommandLine Arguments Pass arguments to main in DOS and UNIX int main int argc char argv int argc number of arguments passed char argv array of strings has names of arguments in order argv o is rst argument Exampe copy input output argc 3 argv O quotcopyquot argv 1 quotinputquot 2 argv quot output quot Tn Aungmsresemed 1 519 143 19147034 2 Us1ng command11m arguments 3 1nc1ude secuoih 4 5 1m manu 1m argc char argv 6 1 Inl ilGilZe variables Ou ine nu unnlepez outF llePtr 1m 1 argv1 is the second argument and is being read a 3 1o 1 391 1 move pnncn quotUsage copy 1n 11e ou 11e 12 else argv2 is the third 13 1 mniepcz 0pen argvi 1 1 quotrquot argument and is being 14 Written to 15 1 oucnlepcz 0pen argvl 2 1 quotwquot a NULL 3c py e 16 17 while I 9etc inrlleptr EDP 18 putc c outrlleptr 19 20 else Loop until End of F119 fge tc a character 21 pnnen quotnle quotsquot Gould 11 I I from 1nFlleP tr and fputc it into 22 outFilePtr 23 else 24 puncn quotnle 39squot Could not be openednquot argv 1 1 25 26 retum o 27 Tn All rigth reserved l 15 Reading Dale from a Sequential Access File Reading a sequential access file Create a FILE pointer link it to the le to read myPtr fopen quotmyFiledatquot quotrquot 7 Use fscanf to read from the le Like scanf except first argument is a FILE pointer fscanf myPtr quot9sd9ss9sfquot ampmyInt ampmystring ampmyFloat Data read from beginning to end File position pointer indicates number of next byte to be readwritten Not really a pointer but an integer value speci es byte location Also called byte offset rewind myPtr repositions le position pointer to beginning of the le byte 0 Tn Aimgmsreseved 1 ngl 11 71 1911 074 2 Readlng and pnnung a sequenclal Elle 3 ulnclude Stdlolh 4 Ouiiine 5 1n M1110 l lnilialize variables 7 1n account a char name 30 1 9 double balance 1 Link pointer 10 me 10 FILE cfPEZi cfptr clientslda Elle pointer 11 12 1 one open quotclientsldatquot NULL 2Regddg15fscanf 13 pzlncn quotnle could nor be opened 14 else i 15 pzlncn Ile1OSe1zsesnquot quotAccountquot quotNamequot quotBalancequot 2 Prim 16 Escan ccpcz IIedeselcI aaccounc name abalance 17 1s whlle lfeo cfpcr i 3 Closefile 19 pnncn quot10d s1357l2 nquot account name balance 20 Escan ccpcz IIedeselcI aaccounc name abalance 21 l 22 23 close ccpcr 24 25 26 retum o 27 Account Name Balance 1 Jones 24 1 Program 0mm 200 Doe 345 67 300 wince 4oo scone 42 16 500 R ch 224 62 1 F191 1113 1911 03 2 credlt 1nqu1ry program 3 1nclude smiled Ouiiine 4 5 1n maan 6 1 Iniiialize variables 1nt request account double balance char name 30 1 2 Open file 10 FILE cfptr move 2 Inpui choice 12 1 ccptr open quotclientsldatquot 13 pr1nt quotnle could not be openednquot 1 915 22 Scan files 5 pr1nt quotEnter requestnquot I 1 L15 accounts wlth zero balancesnquot s wlth cred1t balancesnquot 3 Prim wlth deb1t balancesnquot 2o scan quottoquot reques 22 wmle request 23 scan cfptr 24 abalance account name 26 sw1tch request I ccounts wlth zero 39 29 quotbalancesznquot 31 whlle e0 cfptr 33 1E balance 0 34 prlntn quot910d913597l2 nquot 35 account name balance Ouiiine 37 scan cfptr quot9d9s1 quot 33 account name abalance 22 Scan mes 41 break 3 Prini case 2 43 prlntn quotnAccounts wlth cred1t 39 44 quotbalancesznquot 46 whlle e0 cfptr 1E balance lt o 49 prlntn quot910d913597l2 nquot 50 account name balance 52 scan cfptr quotVedfesfelfquot account name abalance 57 case 3 58 prlntn quotnAccounts wlth deb1t 39 quotbalancesznquot 61 whlle e0 cfptr 63 1E balance gt o 64 pr1nt A quot F 39 account scan cfptz at count break ewlncu cfpt p1nt scan quot sdquot n quot pnntn quotEnd of run1nquot close cfpt retum 0 Tn All ngms reserved azequest Ou ine 3 Close file 23 Enter request 1 L15 accounts wlth zero balanc 2 L15 accounts wlth credlt bala L15 accounts wlth deblt balances 4 End of run 7 1 Accounts wlth zero b 300 whlte alances z o 100 Accounts wlth credlt balances 400 stone 42116 Accounts wlth deblt balances 100 Jones 24198 200 ca 345 167 500 Rich 224 162 4 End of run Tn All ngms reserved Ou ine Program Oum pui l 15 Reading Data from a Sequential Access File ll Sequential access file Cannot be modified without the risk of destroying other data 300 White 000 400 Jones 3287 old data in file If we want to change White s name to Worthington 300 Worthington 000 300 White 000 400 Jones 3287 L Data gets overwritten 300 Worthington 0000nss 3287 Tn Aunghtsresemed l 15 Reading Data from a Sequential Access File Ill Formatted output Different representation in files and screen than internal representation 1 34 890 are all ints but have different sizes on disk Tn Aunghtsresemed 1 L6 Random Access Files 0 Random access files Access individual records without searching through other records Instant access to records in a file Data can be inserted without destroying other data Data previously stored can be updated or deleted without overwriting Implemented using fixed length records equentjal files doonot ham xed length regards byteoffsets S S S S S S bytes bytes bytes bytes bytes bytes Tn Alinghtsresemed l 17 Creating a Random Access File Data Data unformatted stored as raw bytesquot in random access les All data of the same type ints for example use the same memon All records of the same type have a xed length Data not human readable Tn Alinghtsresemed l 17 Creating a Random Access File ll Unformatted IO functions fwrite Transfer bytes from a location in memory to a file fread Transfer bytes from a file to a location in memory fwrite ampnumber sizeof int 1 myPtr o ampnumber Location to transfer bytes from o sizeof int Number of bytes to transfer o 1 For arrays number of elements to transfer In this case quotone elementquot of an array is being transferred o myPtr File to transfer to or from 0 fread similar Tn Allrightsresa39ved 7 Creating a Random Access File Ill 0 Writing structS fwrite myobject sizeof struct mystruct 1 myPtr sizeof Returns size in bytes of object in parentheses To write several array elements Pointer to array as rst argument Number of elements to write as third argument Tn Allrightsresa39ved 1 F19 1111 191 11 I 2 creelan a randomly accessed 11e sequenuslly Qu ine 3 include stdloJI 4 5 struck c11encnaca 6 1m acct um 1 Define slrucl 7 char last anIBI 15 l 8 char first anIBI 10 l L variabe 9 double balance 10 i 11 12 Iniliolize slrucl 12 in M1110 13 14 m 1 2 Open file 15 struck c11encnaca blankcllent o quotquot quotquot 00 16 PM 9 21 Wrile lo file using 17 unformal39led oulpul 18 1f cfptr 0pen quotcred1daquot quot NULL 19 pnncn quotrule could nor be openedn 20 else 3 Close file 21 22 021 1 1 lt 1001 23 wrle blankcllent 24 slzeo Struck clientnata 1 cfPtr 25 26 close cfPtr 27 28 29 retum 0 30 l 18 Writing Data Randomly lo a Random Access File 0 fseek Sets le position pointer to a speci c position fseek myPtr offset symboliciconstant o myPtr pointer to le o offset le position pointer 0 is rst location o symboliciconstant speci es where in le we are reading from 7 SEEKisET seek starts at beginning of le 7 SEELCUR seek starts at current location in le 7 SEEKiEND seek starts at end of le Tn Aungmsresmed r192 11212 1911 12 Writing to a random 1nclude stdlolh Data 1 2 3 4 5 struct cllen 6 nt acc Num 7 s 9 double balance c access 1le Ou ine 1 De ne slrucm 11 Ini olize variables 10 11 12 1n maan 2 Open 399 13 14 FILE cfPtr 2 39l 15 struct cllencnaca cllen o quotquot quotquot 010 39 16 17 1 cfPtr 0pen quotcreditldatquot quot2quot 22wr 31 fie pnncn quotnle could not be openedAnquot 19 else 20 printf IIEnter account numberquot 21 quot 1 to 100 0 to and input n quot 22 scan cllentlacct um 23 24 wh1le cl en a ctNum a 25 p1n quotEnter lastname flzscname balancen2 26 Escan scam quotss1 quot clientlla me 27 an m nzsmame cllentlbalance 23 5eek cfPtr cl1en lace m 1 29 slzeo Struct clientData 30 wr1te cllent Slzeof Struct clientData 1 31 cfPtr 32 Drlntf IIEnter account number n quot 33 scan quotst cllentlacct um 34 Ou lne 35 36 c105e cfPtr 3 dose me 37 33 39 retum o 40 Enter account number 1 to 100 0 to and input 37 Program Oum pui Enter lastname firstname 2 Barker Doug 0200 Enter account number 2 29 Enter lastname firstname 2 Brown Nancy 24254 Enter account number 2 96 Enter lastname firstname Stone Sam 34 98 balance balance balance Tn All ngms reserved Enter account number 2 as Enter 1astname ixzscname balance 2 snub Dave 253 34 Enter account number Program Output 2 33 Enter 1astname ixzscname balance 2 Dunn scacey 314 33 Enter account number 2 0 Tn All nghts reserved 119 Reading Data Sequentially from a Random Access File 0 f read Reads a speci ed number of bytes from a e into memory fread ampclient sizeof struct clientData Can read severa xedsize array eements Provide pointer to array Indicate number of elements to read To read mutipe eements specify in third argument 1 myPtr Tn Armgmsresmed 1 r19 1115 1911 151c 2 Readmg a random access 11e sequenuauy k 3 1nc1ude stdlorln Ou ine 4 5 struck c11emnata 6 1m acc Mum De ne strum 7 char 1asrna 15 1 a char 1rsrname 1o 1 9 double balance 1 Ini olize variables 10 11 12 m mum 2 Read fread 13 14 mm canr 2 Prim 15 struck c11emnata c11em o quotquot quotquot 0 0 16 17 1 ctprr 0pen quotcreditzrdatquot quotrquot pr1m quotnle could not be openedAnquot 20 printf quot96S16S115105nquot quotAcctquot quotLast Namequot 21 quotFirst Namequot quotEalanCEquot 22 23 while e0 cfptr 24 read cllent Slzeof Struck clientData 1 25 cfptr 26 27 1f clientracct um 1 0 28 prin quot96d816s11591012 nquot 29 clientracct um clientrlast ame 30 clientrflrst ame clientrbalance 31 32 33 close cfPtr 34 Ou lne 35 36 rerurn o 3 Close file 37 Acct Last Name First Name Balance mquot 29 Brown Nanc 24 154 Pregr 33 nn sracey 314133 37 Barker 0100 88 Smith Dave 258134 96 Stone Sam 34 r 98 Tn All ngms reserved l 110 Example A Transaction Processing Program Uses random access files to achieve instant access processing of a bank s account information 0 We will Update existing accounts Add new accounts Delete accounts Store a formatted listing of all accounts in a text le Tn Aiinghrsresemed F19 1116 1911 16c Tins program reads a rand double balance In emerCholce void voxd exF 11e FILE 01d u voxd deleteRecord FILE 1m man10 FILE ctpcr 1m cholc 1f ctpcz open quotcred1daquot o om access nIe sequenually cue creates new a punt quotF11e could n i be openednquot else whne choice enterCholceO 5 switch choice NULL Ouiiine 1 De ne slruci 11 Funclion proioivpes 12 lnii ialize variables 13 Link poim er and open le 2 lnpul choice case 1 34 textF11e cfPtr Ou ine 35 break 36 case 2 37 updateRecord cfPtr 38 break 22 Perform action 39 case 3 4o newRecord cfPtr 41 break 3 Close file 42 case 4 j e d P 39 31 Function de nitions 45 46 47 4s close cfPtr 49 so 51 retum 0 52 53 54 void textF11e FILE readPtr 55 56 FILE wrltePtr 5 true cllencnaca cllen 0 0 0 53 59 1f writePtr 0pen quotaccountsltxtquot quotwquot NULL 6o puncn nnle could no be openedln 61 else 62 ewlnd readptr 63 pln wzlcepcz quot6s16s115105n 64 quotAcctquot quotLast Namequot quotFirst quot quot quot 65 66 whlle lfeo readptr Qu ine 67 fread cllent slzeo struct clientData 1 68 readptr 69 70 1f clientlacct um o 3 Function de nitions 71 cpnncn wzlcepcz 26621652115210l2 nquot 72 clientlacct um clientllaStName 73 clientlflrst ame clientlbalance 74 75 76 close wncepcz 77 7s 79 so 81 void updateRecord FILE fPtr 32 33 1n account 34 double zansacclon 85 sczucc cllencnaca cllen o quotquot quotquot Olo L 86 87 print quotEnter account to update 1 100 2 quot as scan quotst aaccoun as 5eek Ptr 90 account 1 slzeo struct clientData 91 SEEK SET 92 read acllenc slzeon strum cllencnaca 1 m 93 94 1f clientlacct um o 95 puncn quotAcount st has no lncomaclonAnn account 96 else 97 pr1n quot96d916s s115910l2 nnquot 9s clle t Num 11am last me 99 11am 1rscname clle t balance 100 pr1n 2ner c arg r p 101 scan Weltquot arransacclo 102 cllent balance ransacclo 103 pr1n quot96d916s115910 2 I 104 clientlacct um clientllast ame 105 clientlflrst ame clientlbalance 106 seek Epcr 107 account 1 slzeon scruct cllencnaca 103 5221 s21 109 wr1e acllenc slzeon scruct cllencnaca 1 110 p 111 112 114v01d deleceRecord 2122 fptr 15 116 scruct cllencnaca cllenc 117 blankcllen 0 quotII 113 1n accouncnum 119 120 pr1n 2ner account number 6 39 121 quotdelete 1 100 z quot 122 scan quottedquot aaccouncnum 123 seek that 124 accouncnum 1 slzeon scruct cllencnaca 125 S221 52139 126 read acllenc slzeon struck cllencnaca 1 Pt Ou ine 3 Function de nitions 127 123 1 clientlacct um 0 129 p1n quotAccount 96d does no existlnquot account um 130 else 5eek Ptr 132 account um 1 slzeo struck clientnata 133 s22xis2T 134 wr1e ablankcnenr 135 slzeo struck clientnata 1 PC 136 137 13s 139v01d newRecord FILE EPEr 140 141 scruc cl1enrnara cl1en 0 0 0 142 In account um 143 pr1nrn quot2nrer new accoun number 1 100 z 144 scan quotst aaccounrnum 145 5eek Mr 146 account um 1 slzeo struck clientnata 147 52217521 14s read acllenc slzeon struck cllencnaca 1 Pt 9 150 1 clientlacct um 0 151 pr1n quotAccount st already concalns infomtlonAn 152 clientlacct um 153 else 154 pr1n 2ner lastname 1rsname balancen quot 155 scan ItestesteliI cllentllast ame cllentlflrst ame 155 n 1 1 Ou ine 3 Function de nitions 157 c11ent r acctNum accountNum Ou ine 158 5eek Eptr clientracct um 1 159 Slzeof Struck clientData SEEKislT 160 wr1te ac11ent 3 Function definitions 161 Slzeof Struck clientData 1 PE 162 163 164 1651nt entercho1ce vo1d 167 1nt menucho1ce 169 pr1nt quotnner your cho1cenquot 170 quot1 store a formatted text le of acounts ca11ednquot 171 quot quotaccountsrtxtv39 for pr1nt1ngnquot 172 quot2 update an accountnquot 173 add a new accountnquot 174 quot4 delete an accountnquot 175 quot5 end programn quot 176 scan quot9 nienucholce 177 return menucho1ce Ou ine After choos1ng opt1on 1 accountsrtxt conta1nsz Acct has Name First Name Balance 29 arown Nancy 4 54 33 Dunn stacey 314133 Program Output 37 aarker Doug 0100 as Sm h nave 253134 96 stone Sam 34193 Enter account to update 1 100 37 37 aarker Doug Enter charge or payment 2 3739 37 aarker Doug 37199 Enter new account number 1 100 22 Enter 1astname 1rstname balance 2 Johnston sarah 247 45 Tn All rigth reserved Um alZ DMa mamw Outline 121 Tn All rig Introduction SeitReterentioi Structures Dynamic Memory Allocation Linked Lists Stocks Queues Trees htsresaved I I i2Jln oduc on Dynamic data structures grow and shrink during execution Linked lists insertions and removals made anywhere Stacks insertions and removals made only at top of stack Queues insertions made at the back and removals made from the front Binary tree s highspeed searching and sorting of data and ef cient elimination of duplicate data items Tn Allnghtsresa39ved 21 122 SelfReferential Structures Selfreferential structures 7 Structure that contains a pointer to a structure of the same type 7 Can be linked together to form useful data structures such as lists queues stacks and trees 7 Terminated with a NULL pointer O 0 Two selfreferential structure objects linked together amp I Data member I I I and pointer NULL pomter pomts to nothmg Tn Aungmsresmed 122 SelfReferential Classes ll struct node int data struct node nextPtr 0 nextPtr points to an object oftype node 7 Referred to as a link7 ties one node to another node Tn Aungmsresmed 22 123 Dynamic Memory Allocation Dynamic memory allocation 7 Obtain and release memon during execution 0 ma 1 1 oc 7 Takes number of bytes to allocate Use sizeof to determine the size of an object 7 Returns pointer of type void A void pointer may be assigned to any pointer If no memory available returns NULL nethr mal 10c sizeof struct node 0 free 7 Deallocates memory allocated by malloc 7 Takes a pointer as an argument 7 free nethr i Tn Aungmsresmed 14 Dynamic Memory Allocation with calloc and realloc Dynamic memory allocation Can create dynamic arrays cal loc nmembers si ze 7 nmembers number of members 7 size size of each member Returns pointer to dynamic array real loc pointerToObj ect newSi ze 7 pointerToObj ect pointer to the object being reallocated 7 newSize new size of the object Returns pointer to reallocated memory Returns NULL if cannot allocate space If newSize 0 object freed If pointerToObj ect 0 acts like malloc Tn Aungmsresmed 23 124 Linked Lists Linked list 7 Linear collection of selfreferential class objects called nodes connected by pointer links 7 Accessed via a pointer to the first node of the list 7 Subsequent nodes are accessed via the linkpointer member 7 Link pointer in the last node is set to null to mark the list s end Use a linked list instead of an array when 7 Number of data elements is unpredictable 7 List needs to be sorted Tn Aungmsresmed 124 Linked Lists ll Types of linked lists 7 singly linked list Begins with a pointer to the first node Terminates with a null pointer Only traversed in one direction 7 circular singly linked Pointer in the last node points back to the first node 7 doubly linked list Two start pointers first element and last element Each node has a forward pointer and a backward pointer Allows traversals both forwards and backwards 7 circular doubly linked list Forward pointer of the last node points to the first node and backward pointer of the first node points to the last node Tn Aungmsresmed 24 1 F191 1213 1912io3tc 2 erat1ng and ma1nta1n1ng a 11st Ou ine 3 1nc1ude stdlorl39n 4 1nc1ude stdllbrln 5 6 struct 11stnode selfrecerent1a1 structure 1 De ne strum 7 ch ata s struct 11stNode nextptr 1 Function 9 proiofvpes 1o 11 ypedef struct 11stnode mstnode L2 lni dize variames 12 ypedef mstnode Llst odeptr 13 14 vo1d 1nsert mstnodeptr char 2 Inpm Chmce 15 char de1ete mstnodeptr char 16 mt islmpty mstnodeptr 17 vo1d pr1ntb1st mstnodeptr 1s vo1d 1nstruct1ons vo1d 19 20 mt man10 21 22 mstnodeptr startptr NULL 23 mt cho1ce 24 char 1tem 25 26 1nstruct1ons display the menu 27 pr1nt I39 quot 2s scan quotv acho1ce 29 3o wh11e cho1ce 3 Qu ine 31 32 sw1tch cho1ce 33 case 1 34 prmtn quotEnter a character 2 switch simemem 35 scan macquot altem 36 1nsert astartptr 1tem 37 pr1ntb1st startptr 33 break 39 case 2 40 1f llslmpty startptr 41 pr1nt quotEnter character to be deleted quot 42 scan quotn wquot a1te 43 44 1f de1ete astartptr 1tem 45 pr1nt quot 31 deletedAnquot 46 pr1ntb1st startptr 47 43 e 49 pr1nt quotc not found nnquot 1tem 50 51 Isa 52 pr1nt quotL15 1 emptyrnnquot 53 54 break 55 default 56 pr1nt quotInva11d choicernnquot 57 1nstruct1ons 0 53 break 59 25 61 pr1nt quot2 quot Ou ine 62 scan quotfedquot cholce 63 64 65 prmtn quotEnd of runrnquot 3 Function de n ons 66 return 0 67 68 69 pr1nt the 1nstruct1ons 7o vo1d 1nstruct1ons vo1d 72 pr1nt quotEnter your cho1ceznquot 73 quot 1 to 1nsert an element 1nto the 115lnquot 74 quot 2 to delete an element from the 115lnquot 75 quot 3 to endlnquot 76 77 7s Insert a new value 1nto the 11st 1n sorted order 79 vo1d 1nsert L1stNodeptr sptr char value s1 L1stNodeptr newptr prev1ousptr currentptr 83 newptr malloc s1eo L1stNode t NULL 1s space ava1lable newptrgtdata value 37 newPrgtnextPr NULL 39 prev1ousptr NULL 90 currentptr SPEZ 92 wh1le currentptr 93 prev1ousptr currentptr walk to 94 currentptr currentptrgtnextptr next node NULL x value gt currentptrgtdata Ou ine 96 3 Function de n ons 101 else 102 prev1ousptrgtnextptr newptr 103 newPrgtnextPr currentptr else 107 pr1nt quot91 not insertedl No memory avallableAnquot value 108 109 110 Delete a 11st element 111char delete L1stNodeptr sptr char value 112 113 LISENOdePEZ previousptr currentptr empPEr 114 115 if value sptr gtdata 116 empPEr SP 117 sptr sptr gtnextPtr dethread the node 11s ree tempptr free the dethreaded node 119 retum value 120 121 else 122 prev1ouspt sptr Ou ine 123 currentptr SPEZ gtnexPr 124 125 while currentptr NULL ampamp cuenPrgtdaa value 126 ev1ouspt currentptr walk to 3 Function de n ons 127 currentptr currentptzmextptr next node 128 129 130 1 currentptr NULL 131 e PC currentptr 132 previousptrM39Aextptr currencPErx39lextpcr 133 free temppt 134 return value 135 136 137 13s retum 39039 139 140 141 Return 1 1f the l1st 1 empty 0 otherw1se 1421nt 1szmpty L1stNodept spt 143 144 return spt NULL 145 146 147 pz1nt the 11 t 148v01d p1ntL1st L1stNodept currentptr 149 150 1 currentptr NULL 1 p1nt quotL1st 1s emtylnnquot 152 else 153 n1nt quotThe 11 t 1 11quot 154 155 wh1le currentptr NULL Ou ine 156 pnntn quot9a gt cuentptgtdata 157 currentpcr currentptrx39lextptr 158 3 Function de n ons 159 160 pnntn NULLnn 161 162 Tn Aungmsresmed 27 Enter your choxce msert an element mate the 115 2 to delete an element from the 115 3 to end 7 Program Ouipul 1 Enter a character a The 115 15 a L 1 Enter a character A The 115 15 A gt a gt NULL 1 Enter a character c The 115 15 A a gt c gt NULL 2 2 Enter character to be deleted D D not i und 2 2 Enter character to be deleted a eted E del The 115 is NULL Tn Aimgmsresemed 125 Slacks vSmck New nodes can be added and removed only at the top Similar to a pile of dishes Lastin rstout LIFO Bottom of stack indicated by a link member to null Constrained version of a linked list push Adds a new node to the top of the stack pop Removes a node from the top Stores the popped value Returns true i aop was successful Tn All rigth reserved I 28 1 F192 1228 191270821 2 amic stack program Ou ine 3 iimomde stdioiln 4 iimomde Stdlibih 5 6 struct stack ode selfreferential structure 1 De ne strum 7 int t3 3 struct stack ode nextptr 1 Function de nitions 9 1 12 iniiioiize variables 11 typedef struct stack ode Stack ode 12 typedef StackNode Stack odeptr 13 2 Input choice 14 void push Stack odeptr int 15 in pop scacmodepcz 16 in isEnlpty scacmodepcz 17 void printstacl Stack odeptr 18 void instructions void 19 20 int main 2 22 scacmodepcz stacthr NULL points to stack top 23 int choice value 24 25 instructions 0 26 printf quot2 n 27 scan quot9 choice 23 29 while choice 3 3 Ou ine 31 switch choice 32 case 1 push value onto stack k 33 print 39Enter an integer quot 34 scan quotfedquot avelue 2 SWitCh51m9m9m 35 push asceokpcz value 36 printstacl stacthr 37 ea 33 case 2 pop value off stack k 39 if liSEnpty stacthr 4o printf quotThe popped value is swimquot 41 pop ampstackPr 42 43 printstacl stacthr 44 brea 45 default 46 print quotInvalid choicei nquot 47 instructions 0 43 break 49 so 51 printf 2 52 scan 39st39 choice 53 54 55 print quotEnd of runinquot 56 retum o 57 53 29 59 pnn he luscmcclons 60 vold 1nsruc10ns vold 61 62 pnncn quotEnter cholceznquot 63 quot1 6 push a value on he sacknquot 64 quot2 6 pop a value off he sacknquot 65 quot3 6 end programnquot 66 67 68 Insert a node a the stack cop 69 vold push Stack odeptr coppcz 11 mm 70 71 Stack odeptr newpcr 72 73 newpcz malloc slzeon scacmode 74 1f newpcz NULL 75 newPrgtdaa mic 76 newPrgtnextPr coppcz 77 topptr newpcr 7s 79 else 30 pnncn quotst no insertedl No memory avallableAnI 31 mm s2 33 Ou ine 3 Function de n ons s4 Remove a node from the stack cop 35 m pop Stack odeptr topptr s7 Stack odeptr emppcz 33 1h popvalue 90 temp topptr 91 popvalue topptr gtdaa 92 topptr topptr gtnexPr 93 free emppcz 94 retum popvalue 95 96 97 man he stack 98 void printstack Stack odeptr currentptr 100 1 currentptr NULL 101 pnncn quotThe stack 1s emptylnn 102 else 103 pnncn quotThe stack lsznquot 104 105 whlle currentptr 106 pnnct cuenpgtdaa 107 currentptr currencpczmexcpcz 108 109 110 pnncn quotNULLnn 111 112 113 Ou ine 3 Function de n ons 114 Is the stack empcy2 Ou ine 115m 1srmpy Stack odeptr oppcz 116 117 retum oppcz NULL 3 Function de n ons 113 Enter choice 1 to push a value on the stack Program Ourpur 2 o pop a value off he stack 3 no end program 7 Enter an 1ncegezz 5 The Stack is 5 NULL gt 2 1 Enter an integer 6 The stack 1 z 6 gt 5 gt NULL 2 1 Enter an integer 4 The stack is 4 gt 6 gt 5 gt NULL 2 2 The popped value 1s 4 The stack is 6 gt 5 gt NULL Tn All ngms reserved 2 Ou lne The popped value 1s 6 The stack is 5 NULL Program Ourpur 2 The popped value 1s 5 The stack 1s empty 2 2 The stack 1s enptyl 4 Invalid choicel Enter choice 1 to push a value on the stack 2 to pop a value off the stack 3 no end program 2 3 End of rum Tn All ngms reserved 126 Queues Queue 7 Similar to a supermarket checkout line 7 Firstin rstout FIFO 7 Nodes are removed only from the head 7 Nodes are inserted only at the tail Insert and remove operations 7 Enqueue insert and dequeue remove Useful in computing 7 Print spooling packets in networks file server requests Tn Alingmsresmed Flgr 1243 19127134 Operating and maintaining a queue Ou ine include stdloihgt include stdlibihgt 1 Define slrucm struct queueNode selfreferential structure char data t t N d hp 1 Function S 2111 eue o e nex I q proiofypes ypedef struct queueNode QueueNode ypedef QueueNode QueueNodePtzr 11 Ini olize variables function prototypes 2 Inpm Cho39ce void printQueue Queueuodeptr int islmpty Queueuodeptr char deq39ueue Queueuodeptr Queueuodeptr void enqueue Queueuodeptr Queueuodeptr char void instructions void in mail10 QueueNodeptr headptr NULL tailptr NULL int choice char item instructions 0 print scan quotedquot zchoice wh11e choice a 3 sthch choxce r a character quot m mtem enqueue aheadptr ataxlptr 1tem prxntQueue headptr break 1 ElsEnDEY headptr l em deq39ueue headptr tallptr prin quotc has been dequeuedrnquot item prxntQueue headptr break default prxntn quotInvalid choicernnquot 1ntruct1ons break prxntn quot2 quot scan quottoquot cholce prxntn quotEnd of runrnquot return m 21 swi tch simemem voxd 1nruc10ns voxd prmt quotEnter your choxceznquot quot 1 o d an 1tem to the queuenquot quot 2 to remove an 1tem from the queuenquot quot 3 to endnquot voxd enqueue Queuenodeptr headptr Queuenodeptr tallptr ch r va1ue Queuenodeptr newptr newptr ma11oc sueon QueueNode 1 islmpy headPtr headPEr newptr else tallptr gtnexPr newptr tallPEr newptr e prxntn quot9a not inserted No memory availablernquot va1 m 3 Function de n ons 96 char dequeue QueueNodepcz headptr QueueNodepcz tallptr 97 99 char value 99 QueueNodepcz emppcz 101 value headptr gtdaa 102 emthzr headptr 103 headptr headptr gtnexp 104 105 if headptr NULL 106 callpcr NULL 107 109 free emppcz 109 retum value Ou ine 3 Function de n ons 110 111 1121n 1szmpcy QueueNodepcz headptr 113 114 retum headptr NULL 115 116 117vo1d p1nQueue QueueNodepcz currentptr 119 119 1 currentptr L 120 p1n quotQueue 1 emptylnnquot 121 else 122 p1n quotThe queue lszn 123 124 wh1le currentptr 1 NULL 125 p1n quot9quot gt cuenPrgtdaa 126 currentptr currentPrgtnextptr 127 3 Function defln ons 129 129 p1n NULLnn 130 131 Enter your cho1cez 1 c d an 1cem 6 the queue 2 6 remove an 1cem from the queue 3 6 end 2 1 Enter a character A The queue 1 z A gt NULL 2 1 Enter a character a The queue 1 z gt a gt NULL 2 1 Enter a character c The queue gt a gt c gt NULL Tn All ngms reserved Program Ouipui Ou ine 2 A has been deq39ueuedi The queue is E C NULL Program Ouipui 2 a has been deq39ueuedi The queue is NULL 2 c has been deq39ueuedi Queue is emptyi 2 2 Queue is empty 2 4 Invalid choice Enter your choice 1 o a an item to the queue 2 0 remove an item from the queue 3 to end 3 End of run Tn All nghts reserved 127 Trees Tree nodes contain two or more links 7 All other data structures we have discussed only contain one Binaiy trees 7 All nodes contain two links None one or both ofwhich may be NULL 7 The root node is the first node in a tree 7 Each link in the root node refers to a child 7 A node with no children is called a leaf node Tn All nghts reserved 127 Trees ll Binary search tree 7 Values in left subtree less than parent 7 Values in right subtree greater than parent 7 Facilitates duplicate elimination 7 Fast searches for a balanced tree maximum of log 2n comparisons 47 25 77 717 3amp4 68 Tn Aungmsresmed 127 Trees Ill 0 Tree traversals 7 Inorder traversal prints the node values in ascending order 1 Traverse the left subtree with an inorder traversal 2 Process the value in the node ie print the node value 7 Preorder traversal 1 Process the value in the node 2 Traverse the left subtree with a preorcler traversal 3 Traverse the right subtree with a preorcler traversal 7 PostOrder traversal 1 Traverse the left subtree with a postorcler traversal 2 Traverse the right subtree with a postorcler traversal 2000 Prentice Hall Inc ng reserved u A Wu H u e ch 3 Traverse the right subtree with an inorder traversal mg 1249 19127194 create a bxnary tree and traverse 1 Ou ine rder morder and postorder k pr 0 1nc1ude stdonn 1nc1ude stdllbrln 1 De ne structure 1nc1ude txme 11 struct treeuode 1 Function struct treeuode leftpcr proiofypes in data struct treeNode rlghtptr 1 2 lni dize variab39es ypedef struct treeNode TreeNode ypedef TreeNode TreeNodePtzr voxd 1nsertNode TreeNodeptr mt voxd 1norder TreeNodeptr voxd preorder TreeNodeptr voxd postorder TreeNodeptr 1m man10 1m 1 xtem TreeNodeptr rootptr NULL srand 1me NULL 1nsert random values between 1 and 15 in the tree Prin quotThe numbers being placed in the tree areznquot Ou ine 0111lt101 item rando 9 15 prxntn quot23dquot item 1nerNode arootptr xtem 139 lnse random elemem s traverse the tree preorder prxntn quotnnThe preorder traversa1 1sznquot preorder rootptr 2 Function calls traverse the tree 1norder 3 Funcnon de nmons prxntn quotnnThe 1norder traversa1 lsznquot 1norder rootptr traverse the tree postorder prxntn quotnnThe postorder traversa1 lsznquot tptr postorder roo return 0 voxd 1nerNode TreeNodeptr treepcr in value 1 treeptr NULL treeptr 1s NULL treeptr malloc sueon TreeNode L n treeptr NULL treeptr gtdata value treeptr gt1e tptr NULL treeptr gtrlghPr NULL 63 lse 64 prlnrn quot9d no insertedl No memory avallableAnquot Qu ine 65 va 66 67 else 68 1 value lt treeptr gtdaa 3 Function de n ons 69 1nsernode m treepcr gt1e Pr value 70 else 1 value gt treepcr gtdaa 71 insert ode amp creeptr gtrlghPr value 72 else 73 prlnrn quotdupquot 74 75 76 vold 1norder TreeNodepcr reepcr 78 1f reePEr NULL 79 1norder reePrgt1e Pr so prlnrn quot936quot reeprgtdaa 81 1norder reePrgtrlghPr 92 93 94 85 vold preorder TreeNodepcr reepcr 87 1f reePEr 39 LL 99 prmrn quot936 reePrgtdata 89 preorder reeprgtle p r 90 preorder reeprgtrlghpr 91 92 93 94 vold posorder Treenodeprr reeprr Ou lne 95 96 1f reepcr I NULL 97 postorder reePrgt1e Pr 3 Function de n ons 98 poscorder reeprgtrlghpr 99 prmrn quot936quot reePrgtdata 100 101 The numbers hem placed 1n the ree are Program Ouipui 7 9 o 6 14 l Odup 13 Odup 7dup The preorder raversal 1s 7 o 6 1 s 14 13 The 1norder raversal 1s 0 1 6 7 s 13 14 The poscorder raversal 1s 1 6 o 13 14 s 7 Tn All ngms reserved Chapter 13 The Preprocessor Outline 131 Tn Introduction The include Preprocessor Directive The define Preprocessor Directive Symbolic Constants The define Preprocessor Directive Macros Conditional Compilation The error and pragma Preprocessor Directives The ii and Operators Line Numbers Predefined Symbolic Constants Assertions All 11ng reserved I 131 Introduction Preprocessing Occurs before a program is compiled Inclusion of other les De nition of symbolic constants and macros Conditional compilation of program code Conditional execution of preprocessor directives Format of preprocessor directives Lines begin with Only whitespace characters before directives on a 2000 Prenuce All 11ng reserved 132 The include Preprocessor Directive 0 i n c l ude Copy of a speci ed le included in place of the directive include ltfi1enamegt Searches standard library for le Use for standard libran les include quot f i lename quot Searches current directow then standard libran Use for userde ned files Used for 7 Loading header les include ltiostreamgt 7 Programs with multiple source les to be compiled together 7 Header le has common declarations and de nitions classes structures function prototypes o include statement in each le Tn Aungmsresemed 133 The define Preprocessor Directive Symbolic Constants def ine Preprocessor directive used to create symbolic constants and macros Symbolic constants When program compiled all occurrences of symbolic constant replaced with replacement text Format def ine identifier replacement text Example define PI 314159 eventhing to right of identi er replaces text ttdefine PI 3 14159 replaces quotPIquot with quot 3 14159 quot probably results in an error 7 Cannot rede ne symbolic constants with more define statements Tn Aunghtsresemed 40 134 The define Preprocessor Directive Macros Macro Operation de ned in define Macro without arguments treated like a symbolic constant Macro with arguments arguments substituted for replacement text macro expanded Performs a text substitution no data type checking Example define CIRCLEiAREZH x PI x x area CIRCLEiAREZH 4 becomes area31415944 Tn Aunghtsresemed 134 The define Preprocessor Direciive Macros II Use parenthesis Without them define CIRCLEiAREZH x p x x area CIRCLEiAREZH c 2 becomes area 314159 c 2 c 2 Evaluates inc0rrectly Multiple arguments define RECTANGLEiAREIH x y x y rectArea RECTANGLEiAREZH a 4 b 7 becomes rectAreaa4b7 Tn Aunghtsresemed 134 The define Preprocessor Directive Macros Ill undef Unde nes a symbolic constant or macro which can later be redefined Tn Aungmsresmed 135 Conditional Compilation Conditional compilation Control preprocessor directives and compilation Cast expressions sizeof enumeration constants cannot be evaluated Structure similar to if if ldefined NULL define NULL 0 endif Determines if symbolic constant NULL de ned If NULL is de ned defined NULL evaluates to 1 If NULL not de ned de nes NULL as 0 Every if ends with endif ifdef short for if definedname ifndef short for if ldefinedname Tn Aungmsresmed 42 135 Conditional Compilation ll 0 Other statements elif equivalent of else if in an if structure else equivalent of else in an if structure 39Comment outquot code Cannot use Use if 0 code commented out endif to enable code change 0 to 1 Tn Aurigmsresmed 135 Conditional Compilation Ill Debugging define DEBUG 1 i fdef DEBUG printfquotVariab1e x dn x endif Defining DEBUG enables code After code is c0rrected remove define statement Debugging statements are now ignored Tn Aurigmsresmed 43 136 The error and pragma Preprocessor Directives 0 error tokens Tokens sequences of characters separated by spaces o quotI like cquot has3tokens Prints message and tokens depends on impementation For exampe when error encountered tokens dispayed and preprocessing stops program does not compie 0 prag39ma tokens Impementation de ned action consult compier documentation Pragmas not recognized by compiler are ignored Tn Aiingmsresemed 137 The and Operators 0 stringization Repacement text token converted to string with quotes define HELLO x printf x n HELLOJohn N 11 ii becomes printf John n Strings separated by whitespace are concatenated in C so we have pn39nth John n 0 concatenation Concatenates two tokens define TOKENCONCAT x Y x y TOKENCONCAT O K becomes OK in All rights reserved 44 1ine renumbers subsequent code lines starting with 133 UneNumbem integer value file name can be included 1ine Lines are numbered from 100 beginning with next 100 quotmyFilecquot source code le For purposes of errors le name is quotmyfi 1e Cquot Makes errors more meaningful Line numbers do not appear in source file Tn Aringmsresmed 139 Predefined Symbolic Constants Five predefined symbolic constants CannotbeLsedinde ineorundef l ti n gangs Base 0 0 iiLIN39Ei The line number of the current source code line an integer iiFILEi of the source file a string iiDATEi The date the source le is compiled a string of the form quotMmm dd yyyyquot such as quotJan 19 2001quot 7 TIM39Ei The time the source le is compiled a string literal of the form quothhmmssquot Tn All rights reserved I 45 1310 ASSGI39I iOhS 0 assert macro Header ltassert hgt Tests value of an expression If 0 false prints error message and calls abort assert 2 lt 10 o If NDEBUG defined All subsequent assert statements ignored def ine Tn All rigth resem NWE G 46 Chapter 1 Introduction to The C Language Outline 11 Introduction 16 Machine Languages Assembly Languages and Highlevel Languages 17 The History 01 C 18 The C Standard Library 19 The Key So ware Trend Object Technology 110 C and CH 112 Other Highlevel Languages 113 Structured Programmin 114 The Basics 01 a Typical C Program Development Environment 118 General Notes About C Q zuuu Premee Hail ine All rights reserved 11 Introduction 7 We Will learn the C programming language 7 Learn LtueLuieilA I and proper A I techniques 7 This course is appropriate for 7 Technically oriented people with little or no programming experience 7 Experienced programmers who want a deep and rigorous treatment of the language zunu Premee Hail In All rights reserved 16 Machine Languages Assembly Languages and Highlevel Languages Three types of programming languages 1 Machine languages 7 Strings of numbers giving machine speci c instructions 7 Example 13 0 0 04 2 7 7 4 l 4 0 0 5 9 3 4 l 9 l 2 0 0 2 7 4 0 2 7 2 Assembly languages Englishlike abbreviations representing elementary computer operations translated via assemblers 7 Example LOAD BAS E PAY AD D OVE R PAY STORE GRO S S PAY zuuu Premee Ha11ine All ngms reserved 16 Machine Languages Assembly Languages and Highlevel Languages ll Highlevel languages Similar to everyday English and use mathematical notations translated via compilers Example grossPay basePay overTimePay Interpreters directly execute program lines without compilation zunu Premee Han In All ngms reserved 17 History of C C 7 Evolved by Ritchie from two previous programming languages BCPL and B 7 Used to develop UNIX 7 Now most operating systems written with C or C 7 Hardware independent portable 7 By late 197039s C had evolved to quotTraditional C Standardization 7 Many slight variations of C existed and were in compatible 7 Committee formed to create a quotunambiguous machine independent de nition 7 Standard created in 1989 updated in 1999 zuuu Premiere Hall In Allnghts reserved 18 The C Standard Library 0 C programs consist of piecesmodules called functions 7 A programmer can create his own functions Advantage the programmer knows exactly how it works Disadvantage time consuming 7 Programmers will often use the C library functions Use these as building blocks 7 Avoid reinventing the wheel If a premade mction exists generally best to use it rather than write your own Library mctions carefully written ef cient and portable zunu Premiere Hall In Allnghts reserved 19 The Key Software Trend Object Technology Objects 7 Reusable software components that model items in the real world 7 Meaningful software units Date objects time objects paycheck objects invoice objects audio objects video objects le objects record objects etc Any noun can be represented as an object 7 Very reusable 7 More understandable better organized and easier to maintain than procedural programming 7 Favor modularity zuuu Premiere Han In Allnghts reserved 110 C and C C 7 Superset of C developed by Bjarne Stroustrup at Bell Labs 7 quot Spruces up C and provides objectoriented capabilities Objects reuseable software components 7 Objectoriented design very powerful 10 to 100 fold increase in productivity 7 Dominant language in industry and university Learning C 7 Because C includes C some feel it is best to master C then learn C 7 Chapter 15 of Deitel amp Deitel begins an introduction to CH zunu Premiere Han In Allnghts reserved 112 Other Highlevel Languages A few other highlevel languages have achieved broad acceptance 0 FORTRAN 7 Scienti c and engineering applications 0 COBOL 7 Used to manipulate large amounts of data Pascal 7 Intended for academic use 0 Java 7 Obj ectoriented developed by Sun Microsystems 7 Good for creating web pages with dynamic and interactive content zuuu Frames Han In Allnghts reserved 113 Structured Programming Structured programming 7 Disciplined approach to writing programs 7 Clear easy to test and debug and easy to modify 7 examples Pascal and Ada Multitasking 7 Specifying that many activities run in parallel 7 Not supported directly by C and C Most operating systems now support multitasking zunu Frames Han In Allnghts reserved 114 Basics of a Typical C Program Development Environment Phases of C Programs m gt g In gt Eggf g m 2 Preprocess M gt we WWW 3 n zifmgngqyk lb zsv mime 4 Link 5 Load 1151me 6 Execute We MW mmm mmm Wee m was We WW executes zuuu Premee Ha11ine All ngms reserved 118 General Notes About C Program clarity 7 Programs that are convoluted are difficult to read understand and modify 0 C is a portable language 7 Programs can run on many different computers 7 However portability is an elusive goal We Will do a careful walkthrough of C 7 Some details and subtleties not covered 7 If you need additional technical details Read the C standard document Read other books and materials on C e weenquot Hm Anagrams Chapter 2 Introduction to C Programming Outline 21 Introduction 22 A Simple C Program Printing a Line oflext 23 Another Simple C Program Adding Two Integers 24 Memory Concepts 25 Arithmetic in C 26 Decision Making Equality and Relational Operators zuuu Premee Han In All nghrs reserved 21 Introduction C programming language 7 Structured and disciplined approach to program design Structured programming 7 Introduced in chapters 3 and 4 of Deitel amp Deitel 7 Used throughout our discussion on C programming zunu Premee Han irre All nghrs reserved 22 A Simple C Program Printing a Line of Text 2 or a A hast fvg m Li C w J mci uae ltstdiolquotigt i F ihgmfei no printf welcome to C1n 1 10 return 0 Welcome to c1 0 Comments 7 Text surrounded by and is ignored by computer 7 Used to describe program 0 include ltstdio hgt 7 Preprocessor directive tells computer to load contents of a certain le lt s tdio hgt allow Wndard inputoutput operations zuuu Prmtlce Ha11ine All nghrs reserved 22 A Simple C Program Printing a Line of Text ll 0 int main C programs contain one or more functions exactly one of which must be maln Parenthesis used to indicate a function int means that main quotreturnsquot an integer value 7Braces indicate a block 0 The bodies of all functions must be contained in braces zunu Prmtlce Ha11ine Allnghts reserved 22 A Simple C Program Printing a Line of Text Ill 0 printf quotWelcome to C1nquot Instructs computer to perform an action 0 Specifically prints string of characters Within quotes Entire line called a statement 0 All statements must end With a semicolon escape character 0 Indicates that printf should do something out of the ordinary 0 n is the newline character zuuu Prmtice Hail in Allnghts reserved 22 A Simple C Program Printing a Line of Text IV 0 return 0 7 A way to eXit a function return 0 in this case means that the program terminated normally Right brace 7 Indicates end of main has been reached 0 Linker 7 When a function is called linker locates it in the library 7 Inserts it into object program 7 If function name misspelled linker will spot error mm mm nggaplsxgtitegragni39 function in library 72 Sum is 117 Enter 1 ISt integer 45 Enter se cond luteger 2mm Premee Ha111ne All rights reserved Program Output 0 zunu Premee Hall 23 Another Simple C Program As before 7 Comments include ltstdiohgt and main 0 int integerl 7 Declaration of variables stored Adding Two Integers digit and underscores case sensitive If not sxgrtafr le error In All n gms r integerz SUIII 0 Variables locations in memory where a value can be int means the variables can hold integers 1 3 0 47 integerl integer2 sum variable names identifiers Identi ers consist of letters digits cannot begin with a 7 Declarations appear before executable statements 23 Another Simple C Program Adding Two Integers ll 0 scanf quotdquot ampinteger1 Obtains value from user 0 scanf uses standard input usually keyboard This scanf has two arguments 0 d indicates data should be a decimal integer 0 ampintegerl location in memory to store variable 0 amp is confusing in beginning just remember to include it With the variable name in scanf statements It Will b cussed later zuuu Premee Han me All rights reserved 23 Another Simple C Program Adding Two Integers Ill 0 assignment operator 7 Assigns value to a variable 7 Binary operator has two operands sum variablel variab1e2 sumgdsvariablel variab1e2 7 Variable receiving value on left 0 printf IISum is dnquot sum 7 Similar to scanf 95d means decimal integer will be printed 0 sum speci es what integer will be printed 7 Calculations can be performed inside printf statements printf IISum is dnquot integerl integer2 zunu Premee Han In All rights reserved 24 Memory Concepts 0 Variables 7 Variable names correspond to locations in the computer s memory 7 Every variable has a name a type a size and a value 7 Whenever a new value is placed into a variable through scanf for example it replaces and integerl vu39augc LllUlll A visual representation zuuu Frantice Han In Allnghts reserved 25 Arithmetic Arlthmetlc calculatlons are used 1n most programs 7 Use for multiplication and for division 7 Integer division truncates remainder 7 5 evaluates to l 7 Modulus operator returns the remainder 7 9 5 evaluates to 2 Operator precedence 7 Some arithmetic operators act before others ie multiplication before addition 0 Use parenthesis when needed 7 Example Find the average of three variables a b and c Donotuse a b c 3 znnnprmucega1umAilnwsresemeqku 4 h 4 r q 25 Arithmetic ll 0 Arithmetic operators zuuu Premee Han ine Allnghts reserved 26 Decision Making Equality and Relational Operators Executable statements 7 Perform actions calculations inputoutput 7 Perform decisions 0 May want to print quotpassquot or quotfailquot given the value of a test grade 0 if control structure 7 Simple version in this section more detail later 7 If a condition is true body of if statement is executed 0 0 is false nonzero is true 7 Control always resumes after the if structure 0 Keywords 7 Special words reserved for C 7 Cannot be used 39 ti ers or variable names zunu Premee Han In All nghts reserved 26 Decision Making Equality and Relational Operators ll 2mm Prmtice Ha111ne All nghis reserved Outline 1 Declare Variables 2 Input 1 if siaiemenls 3 Prim Ilile l wserj m 9 61 Exit main h er we ntegers and I the relatlenshlps they satisfy wlll tell you Ploglam Output 3 7 v r m s 3 rs less than or equal to 7 Enter two ntegers and I will tell you the relationships they satisfy 22 12 to 12 22 5 net equal 22 is greater than 12 22 is greater than or equal to 12 zuuu Prantme Ha11lhe All ghts reserved 26 Complete C Keywords weanquot um hlnwsresemu Chapter 3 Structured Program Development in C Outline 31 Introduction 32 Algorithms 33 Pseudocode 34 Control Structures 35 The IT Selection Structure 36 The ITElse Selection Structure 37 The While Repetition Structure 38 CounterControlled Repetition 39 SentinelControlled Repetition 310 Nested Control Structures 311 Assignment Operators 312 Increment and Decrement Operators zuuu Premee Hall ine All rights reserved 31 Introduction 0 Before writing a program 7 Have a thorough understanding of problem 7 Care illy planned approach for solving it 0 While writing a program 7 Know what building blocks are available 7 Use good programming principles zunu Premee Hall In All rights reserved 32 Algorithms Computing problems 7 All can be solved by executing a series of actions in a speci c order 0 Algorithm procedure in terms of 7 Actions to be executed 7 Order in which these actions are to be executed Program control 7 Specify order in which statements are to executed zuuu Prmtice Han In Allnghts reserved 33 Pseudocode Pseudocode 7 Arti cial informal language that helps us develop algorithms 7 Similar to everyday English 7 Not actually executed on computers 7 Helps us think out a program before writing it Easy to convert into a corresponding C program Consists only of executable statements zunu Prmtice Han In Allnghts reserved 34 Control Structures I Sequential execution 7 Statements executed one after the other in the order written I Transfer of control 7 When the next statement executed is not the next one in sequence 7 Overuse of goto led to many problems I Bohm and Jacopini 7 All programs written in terms of 3 control structures I Sequence structure Built into C Programs executed sequentially by default Repetition structures Three types while dowhile and for I No goto statements I These are C keywords zuuu Premiere Han In Allnghts reserved Selection structures C has three types 1 f i felse and switch 34 Control Structures II I Flowchart 7 Graphical representation of an algorithm 7 Drawn using certain specialpurpose symbols connected by arrows called owlines 7 Rectangle symbol action symbol indicates any type of action 7 Oval symbol indicates beginning or end of aprogram or a section of code circles I Singleentrysingleexit control structures 7 Controlstructure stacking Connect exit point of one control structure to entry point of the next 7 Control structure nesting contain control structures can contain other control structures 7 Only 7 control structures in all only 2 to combine them 7 Makes programs easy to build zunu Premiere Han In Allnghts reserved 35 The i f Selection Structure 0 Selection structure 7 Used to choose among alternative courses of action 7 Pseudocode f39studem s grade is greater than or equal to 60 Print Passed 0 If condition true 7 Print statement executed and progmm goes on to next statement 7 If false print statement is ignored and the progmm goes onto the next statement 7 Lndenting makes progmms easier to read C ignores whitespace characters Pseudocode statement in C if grade gt 60 printf quotPassednquot 7 C code corresponds closely to the pseudocode zuuu Prmtlce Han In Allnghts reserved 35 The i f Selection Structure ll Diamond symbol decision symbol indicates decision is to be made Contains an expression that can be true or fal se I Test the condition follow appropriate path 0 i f structure is a singleentrysingleexit structure Still follows the general actiondecision programming model decision Canbefmadeifo any expression zero ta 5 e grade gt 60 p l quot Passed nonzero true Example 339 4 is true zunu Prmtlce Han In Allnghts reserved 36 The i f e1 se Selection Structure 0 if 7 Only peIforms an action if the condition is true 0 ifelse 7 A different action When condition is true than When condition is false Psuedocode Ifstudem x grade is greater than or equal to 60 Print Passed else Prim Failed 7 Note spacingindentation conventions Ccode if grade gt so pin quotPassadnquoti se pinf quotPaiiadnquot zuuu Prmttce Han In Allnghts reserved 36 The if else Selection Structure ll false true grade gt so prlnt Passed I 0 Ternary conditional operator 7 Takes three arguments condition value if true value if false 7 Our pseudocode could be written printf quotsnquot grade gt 60 quotPassedquot quotFailedquot OR grade gt 50 printf Passednquot printf Failednquot zunu Prmttce Han In Allnghts reserved 20 36 The if else Selection Structure Ill 0 Nested ifelse structures 7 Test for multiple cases by placing i f else selection structures inside i felse selection structures Ifstudent s grade is greater than or equal to 90 Print A quot eLve Kstudent s grade is greater than or equal to 80 r39nt B eLve If student s grade is greater than or equal to 70 Print C else Ifstudent s grade is greater than or equal to 60 Print D eLve Print F 7 Once condition is met rest of statements skipped 7 Deep indentation usually not used in practice zuuu Premee Ha111rre All nghts reserved 36 The i felse Selection Structure IV 0 Compound statement 7 Set ofstatements Within apair ofbraces 7 Example if grade gt 6 printf quotpassedn e1se printf quotFailednquot printf quotYou must take this course againnquot 7 Without the braces printf quotYou must take this course againnquot would be automatically executed 0 Block compound statements with declarations zunu Premee Ha111rre All nghts reserved 21 36 The i f else Selection Structure V Syntax errors 7 Caught by compiler Logic errors 7 Have their effect at execution time 7 Nonfatal program rims but has incorrect output 7 Fatal program exits prematurely zuuu Prmttce Hall In Allnghts reserved 37 The while Repetition Structure Repetition structure 7 Programmer specifies an action to be repeated While some condition remains true 7 Psuedocode While there are more item on myshopping list Purchase next item and cross it o my list while loop repeated until condition becomes false zunu Prmttce Hall In Allnghts reserved 22 37 The while Repetition Structure ll 0 Example int product 2 while product lt 1000 product 2 product product 2 product product lt 1000 zuuu Premee Han ine All rights reserved 38 Formulating Algorithms CounterControlled Repetition Countercontrolled repetition Loop repeated until counter reaches a certain value De nite repetition number of repetitions is known Example A class often students took a quiz The grades integers in the range 0 to 100for this quiz are available to you Determine the class average on the quiz Pseudocode Set total to zero Set grade counter to one While grade eounteris less than or equal to ten Input the next gra e Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average 0 zunu Premee Hall1nc All rights reserved 23 M ze Variables 2 Execute Loop Output results Outline Program Output a nnnvrmn H w Allnghtsreserved 24 39 Formulating Algorithms with TopDown Step 39 SentinelControlled Repetition E 0 m U m 2quot 3 m 3 m 3 Problem becomes Develop a classaveraging program that will process an arbitrary number of grades each time the program is run 7 Unknown number of students 7 How will the program know when to end Use sentinel value 7 Also called signal value dummy value or ag value 7 Indicates end of data entry 7 Loop ends when sentinel inputted 7 Sentinel value chosen so it cannot be confused with a regular input such as 1 in this case 7 used for inde nite repetition zuuu Premee Hall ine All rights reserved 39 Formulating Algorithms with TopDown Stepwise Refinement SentinelControlled Repetition ll Topdown stepwise re nement 7 Begin with a pseudocode representation of the top Determine the class averagefor the quiz 7 Divide top into smaller tasks and list them in order Initialize variables Input sum and count the quiz grades Calculate and print the class average Many programs have three phases 7 Initialization initializes the program variables 7 Processing inputs data values and adjusts program variables accordingly 7 Termination calculates and prints the nal results 7 This helps the breakup of programs for topdown re nement zunu Premee Hall in All rights reserved 25 39 Formulating Algorithms with TopDown Stepwise Refinement III 0 Re ne the initialization phase from Initialize variables to Initialize total to zero Initialize Counter to zero Re ne Input sum and count the quiz grades to Input the rst grade poniny the ventinel Whi e t e uxer a notaxyet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade possibly the sentinel Re ne Calculate and print the class average to Ifthe counter is not equal to zero Set the average to the total d39vided by the counter Print the average elxe Print No grades were entered 2mm Premise Ha11ine All ngms reserved Outline 1 lnilializeVariables Gel user input 1 Pe orrn Loop 26 Outline 31 Prim Results Program Output Enter grade 1 to Enter grade 71 to en Enter grade 1 c n as Enter grade 1 to end 70 Enter reds e1 to end 54 Enter grade 1 to endz39 93 Enter grade 71 to end 219 Enter gre nd e1 as ex to e V Class average 1524251 2mm Premiere Hall In All ngms reserved 3 Calculate Average 310 Nested control structures I Problem 7 A college has alist oftest results 1 pass 2 fail for 10 students 7 Write a program that analyzes the results I If more than 8 students pass print quotRaise Tuitionquot I Notice that 7 The program must process 10 test results Countercontrolled loop will be used 7 Two counters can be used I One for number of passes one for number of fails 7 Each test result is a number7either a 1 or a 2 I If the number is not a 1 We assume that it is a 2 e nnnvrpun Hm Aimsresema 27 310 Nested control structures ll 0 Top level outline Analyze exam results and decide rftuition should be raised 0 First Re nement Initialize variables Input the ten quiz grades and count passes and failures Print a summary ofthe exam results and decide iftuition should be raised 0 Re ne Initialize variables to Initialize passes to zero Initializefailures to zero Initialize student counter to one Q zuuu Premee Ha111ne All nghts reserved 310 Nested control structures Ill Refine Input the ten quiz grades and count passes andfailures to While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter Refine Print a summaiy afthe exam results and decide iftuitian should be raised to Print the number of passes Print the number of failures If more than eight students passed Print Raise tuition zunu Premee Han In All nghts reserved 28 Outline 1 Iniua Ize Variables Input data and count passestailures 3 Print Iesulls Ehter Outline Ploglam Oulpul 3552 EaJ lx 1 555243111 2 Ref ssegl 5 Failed A a nnnvrmn H w Allnghtsreserved 311 Assignment Operators Assignment operators abbreviate assignment expressions c c 3 can be abbreviated as c 3 using the addition assignment operator 0 Statements of the form variable variable operator expression can be rewritten as variable operator expression Examples of other assignment operators d4 dd4 e5 ee5 3 f3 g9s9 gg9s9 zuuu Prmtlce Han In Allnghts reserved 312 Increment and Decrement Operators Increment operator can be used instead of c 1 Decrement operator can be used instead of c 1 Preincrement 7 Opemtor is used before the variable c or c 7 Variable is changed then the expression it is in is evaluated Postincrement 7 Opemtor is used a er the variable c or c 7 Expression executes then the variable is changed If c 5 then printf quot515dquot c I Prints 6 printf quot515dquot c I Prints 5 7 In either case c now has the value of 6 zunu Prmtlce Han In Allnghts reserved 30 312 Increment and Decrement Operators ll 0 When variable is not inside an expression 7 Preincrementing and postincrementing have the same effect c cout ltlt c and c cout ltlt c have the same effect zuuu Premiere Ha11ine All nghrs reserved I I Chapter 4 Program Control Outline 41 zunu Premiere Hail In All nghrs Introduction The Essentials of Repetition CounterControlled Repetition The For Repetition Structure The For Structure Notes and Observations The Switch MultipleSelection Structure The DoWhile Repetition Structure The break and continue Statements Logical Operators Equality and Assignment Operators Structured Programming Summary reserved I I 31 41 Introduction 0 Should feel comfortable writing simple C programs 0 Coverage 7 Repetition in greater detail 7 Logical operators for combining conditions 7 Principles of structured programming zuuu Prmtice Hail in Allnghts reserved 42 The Essentials of Repetition Loop 7 Group of instructions computer executes repeatedly while some condition remains true Countercontrolled repetition 7 De nite repetition know how many times loop will execute 7 Control variable used to count repetitions Sentinelcontrolled repetition 7 Inde nite repetition 7 Used when number of repetitions not known 7 Sentinel value usually indicates quotend of data zunu Prmtice Hail in Allnghts reserved 32 43 Essentials of CounterControlled Repetition Countercontrolled repetition requires 7 name of a control variable or loop counter 7 initial value of the control variable 7 condition that tests for the nal value of the control variable ie Whether looping should continue 7 increment or decrement by which the control variable is modified each time through the loop zuuu Frames Hall in Allnghts reserved 43 Essentials of CounterControlled Repetition ll 0 Example int Counter 1 initialization while counter lt 10 repetition condition printf quotdnquot counter counter increment 7 int counter 1 names counter declares it to be an integer reserves space for it in memory and sets it to an initial value of 1 zunu Frames Hall in Allnghts reserved 33 44 The for Repetition Structure 0 Format when using for loops statement 7 good for countercontrolled repetition Example for int counter 1 counter lt 10 counter printf quotdnquot counter 7 Prints the integers from one to ten zuuu Prmttce Hall in Allnghts reserved for initialization loopContinuationTest increment o s39ei39riicolon ast aft r 1 expression 44 The for Repetition Structure ll 0 For loops can usually be rewritten as while loops initialization while loopContinuationTest statement increment Initialization and increment 7 Can be commaseparated lists for int i 0 j 0i j i lt 10 j i printf quotdnquot j i zunu Prmttce Hall in Allnghts reserved 34 45 The For Structure Notes and Observations Arithmetic expressions 7 Initialization loopcontinuation and increment can contain arithmetic expressions If x 2 andy 10 forjxjlt4xyjyx is equivalent to forj2jlt80j5 quotIncrementquot may be negative decrement If loop continuation condition initially false 7 Body of for structure not performed 7 Control proceeds with statement after for structure zuuu Prmttce Han In Allnghts reserved 45 The For Structure Notes and Observations ll Control variable 7 Often printed or used inside for body but not necessary 0 for owcharted like whil e 0 often used for infinite loops zunu Prmttce Han In Allnghts reserved 35 Outline 46 Examples Using the for Structure Program lo sum the even numbers mm 2 lo 100 Sum is 2550 Program Oulpul 2mm Premee Han ine All rights reserved 47 The switch MultipleSelection Structure 0 switch 7 Useful when a variable or expression is tested for all the values it can assume and different actions are taken Format 7 Series of case labels and an optional default case switch value case 1 actions case 2 actions default actions 7 break causes exit from structure e nnnvreun Hm Minetsresema 36 47 The switch MultipleSelection Structure ll 2mm Pranuce Ha111ne All ghts reserved Outline 1 lnitlalizevariables Input data 1 Use switch loop to update coun 37 Outline gamma 1 Use switch loop to update count Prim results Outline Ehter uh e lancer rad 55 Enter the 13ng character to and input A Ploglam Oulpul nmuwomm E Incorrect letter grade entered Eneer a new grade 19 A E Tgtals gar each leptergrede are A u Hmummi a nnnvrmn H w Allnghtsreserved 38 48 The dowhile Repetition Structure 0 The do whi l e repetition structure 7 Similar to the whi 1e structure 7 Condition for repetition tested after the body of the loop is performed All actions are performed at least once Format do statement while condition 7 Good practice to put brackets in even if not required zuuu Prmttce Han In Allnghts reserved 48 The dowhile Repetition Structure ll 0 Example letting counter 1 do printf quot35d quot counter while counter lt 10 Prints the integers from 1 to 10 zunu Prmttce Han In Allnghts reserved 39 48 The dowhile Repetition Structure Ill true false 2mm Pranuce Ha111ne All ghts reserved Plogram Oulpul a nnnvrenn H w Allnghtsreserved 40 49 The break and continue Statements 0 break 7 Causes immediate exit from a while for dowhile or swi tch structure 7 Program execution continues with the first statement after the structure 7 Common uses of the break statement Escape early from a loop Skip the remainder of a switch structure zuuu Frantice Han In Allnghts reserved 49 The break and continue Statements II 0 c on t i nu e 7 Skips the remaining statements in the body of a while for or dowhile structure Proceeds with the next iteration of the loop while and dowhile Loopcontinuation test is evaluated immediately after the continue statement is executed for structure Increment expression is executed then the loopcontinuation testis evaluated zunu Frantice Han In Allnghts reserved 41 Outline 1 Initialize Variable 2 Loop Prim Program Output 1 2 3 g 0 Used Contlnue e0 skrp EIJntng the value 5 2mm Pranute Ha111ne All ngms reserved 410 Logical Operators 0 ampamp logical AND 7 Returns true ifboth conditions are true 0 logical OR 7 Returns true if either of its conditions are true 0 logical NOT logical negation 7 ReveIses the truthfalsity of its condition 7 Unary operator has one operand Useful as conditions in loops Expression Result true 55 false false true false true lfalse true o nnnvreun Hm engagement 411 Confusing Equality and Assignment Operators Dangerous error 7 Does not ordinarily cause syntax errors 7 Any expression that produces a value can be used in control structures 7 Nonzero values are true zero values are false Example if payCode 4 printf quotYou get a bonustnquot Checks paycode if it is 4 then a bonus is awarded zuuu Prmttce Hall in Allngqts reserved 411 Confusing Equality and Assignment Operators II 0 Example replacing with if payCode 4 printf quotYou get a bonustnquot 7 This sets paycode to 4 7 4 is nonzero so expression is true and bonus awarded no matter what the paycode was 7 Logic error not a syntax error zunu Prmttce Hall in Allngqts reserved 43 411 Confusing Equality and Assignment Operators Ill lvalues 7 Expressions that can appear on the le side of an equation 7 Their values can be changed such as variable names I x 4 rvalues 7 Expressions that can only appear on the right side of an equation 7 Constants such as numbers I CannotWIite 4 x 7 lvalues can be used as rvalues but not vice versa 39 Y x Q zuuu Prmttce Hall in Allnghts reserved 412 StructuredProgramming Summary Structured programming 7 Easier than unstructured programs to understand test debug and modify programs 0 Rules for structured programming 7 Rules developed by programming community 7 Only singleentrysingleexit control structures are used 7 Rules 1 Begin With the simplest owchart 2 Any rectangle action can be replaced by two rectangles actions in sequence 3 Any rectangle action can be replaced by any control structure sequence 1 f i f else swi tch while dowhile or for 4 Rules 2 and 3 can be applied in any order and multiple times zunu Prmttce Hall in Allnghts reserved 44 412 StructuredProgramming Summary ll Rl aZ Any rectangle can be replaced by No rectangles in Sequencez B egin thequot Rule simplest owchart Ru e 2 Rue 2 Rue 2 i i zuuu Pranuce Han In Allnghts reserved 412 StructuredProgramming Summary Ill Rule 3 Replaiqe anyraatgnglg with a39 c011161 s 11ct1ra i C z 2 i Q zunu Pranuce Han In Allnghts reserved 45 412 StructuredProgramming Summary IV 0 All programs can be broken down into 3 parts Sequence trivial Selection if ifelse or switch Repetition whi 1e dowhi 1e or for 7 Any selection can be rewritten as an if statement and any repetition can be rewritten as a while statement Programs are reduced to 7 Sequence 7 i f structure selection 7 whi l e structure repetition I The control structures can only be combined in two ways nesting rule 3 and stacking rule 2 7 This promotes simplicity zuuu Premiere Hall irre All nghrs reserved Chapter 5 Functions Outline 52 Program Modules in C 53 Math Library Functions 39 s 54 Function 55 Function De nitions 56 Function Prototypes 57 Header Files 58 Call by Value and Call by Reference 59 Random Number Generation 511 Storage Classes 512 Scope Rules 513 Recursion 515 Recursion vs Iteration zunu Premiere Hall In All nghrs reserved 46 51 Introduction Divide and conquer Construct a program from smaller pieces or components Each piece more manageable than the original program zuuu Premee Ha11ine Allnghts reserved 52 Program Modules inc 0 Functions 7 Modules in C 7 Programs written by combining userde ned functions with library functions 0 C standard library has a wide variety of functions 0 Makes pro grammer39s job easier avoid reinventing the wheel 0 Function calls 7 Invoking functions 0 Provide function name and arguments data 0 Function performs operations or manipulations 0 Function returns results 7 Boss asks worker to complete task 0 Worker gets information does task returns result 0 Information hidin boss does not know details zunu Premee Ha11ine All ngms reserved 47 53 Math Library Functions Math library ll lCthl lS 7 perform common mathematical calculations include ltmath hgt Format for calling ll lCthl lS FunctionName argument 0 If multiple arguments use commaseparated list printf quot2fquot sqrt 9000 0 Calls function sqrt which returns the square root of its argument 0 All math functions return data type double 7Arguments may be constants variables or expressions 5 znuu Prentice Hall In Allnghts reserved 54 Functions Functions 7 Modularize a program 7 Variables declared inside functions are local variables 0 Known only in function defined 7 Parameters 0 Communicate information between functions 0 Local variables 0 Bene ts 7 Divide and conquer Manageable program development 7 Software reusability 0 Use existing functions as building blocks for new programs 0 Abstraction hide internal details library functions znnn PrenticeHall In Allnghtsreserved I 7 Avoids code repetition 48 55 Function Definitions Function de nition format returnvalue type functionname parameterlist declarations and statements 7 Functionname any valid identifier 7 Retumvaluetype data type of the result default int ovoid function returns nothing 7 Parameterlist comma separated list declares parameters default int zuuu Premee Han ine Allnghts reserved 55 Function Definitions II Function de nition format continued returnvaluewa functionname parameterlist declarations and statements 7 Declarations and statements function body block 0 Variables can be declared inside blocks can be nested 0 Function can not be de ned inside another function 7 Returning control 0 If nothing returned return 7 or until reaches right brace 0 If something returned return ssion zunu Premee Han In All ngms reserved 49 Outline 1 Function prototype 3 parameters 2 lnputvalues 21 Call function 0 Function definition Enter phlee integers 22 35 17 Magnmum 15 as Q 2mm Premee Han ine All rights reserved 56 Function Prototypes Function prototype 7 Function name 7 Parameters What the function takes in 7 Return type data type function returns default int 7 Used to validate functions 7 Prototype only needed if fimction de nition comes after use in program int maximum int int int Takes in 3 ints Returns an int Promotion rules and conversions 7 Converting to lower types can lead to errors a nnnvrenn Hii iquot Allnghtsreserved 57 Header Files Header les 7 contain function prototypes for library functions ltstdlibhgt ltmathhgt etc 7 Load with include lt filenamegt include ltmath hgt 0 Custom header les 7 Create file with functions 7 Save as filename h 7 Load in other files with include quot filename hquot 7 Reuse functions zuuu Premee Hall ine All ngms reserved 58 Calling Functions Call by Value and Call by Reference 0 Used when invoking mctions Call by value 7 Copy of argument passed to function 7 Changes in function do not effect original 7 Use when function does not need to modify argument 7 Avoids accidental changes 0 Call by reference 7 Passes original argument 7 Changes in function effect original 7 Only used with trusted functions For now we focus on call by value zunu Premee Hall In Allnghts reserved 59 Random Number Generation 0 rand ll lCthl l 7 Load ltstdlibhgt 7 Returns quotrandomquot number between 0 and RANDMAX at least 32767 i rand 7 Pseudorandom Preset sequence of quotrandomquot numbers 0 Same sequence every time program is executed Scaling 7 To get a random number between 1 and n 1randn 0 rand 95 n returns a number between 0 and n 1 0 Add 1 to make random number between 1 and n E znuu Prentice Halllln ungran 6 n0 bW 1 and 6 59 Random Number Generation ll 0 srand mction lt s tdl ib hgt 7 Takes an integer seed jumps to location in quotrandomquot sequence srand seed srand time NULL load lt time hgt 0 time NULL time program was compiled in seconds 0 quotrandomizesquot the seed zunu Prmtlce Han In Allnghts reserved M 1 Initialize seed 2 Inputvalue for seed 21 Use srand to change random sequence 22 Define Loop 3 Generate and output random numbers Mex Sega s7 Outline 5 1 4 5 2 1 5 1 5 4 Enter seed 867 2 s 1 a Program Output 1 1 3 E 2 Ehrer seeds 67 IE 1 4 5 2 1 6 1 39E 4 a nnnvrmn H w Allnghtsreserved 510 Example A Game of Chance Craps simulator Rules 7 Roll two dice 7 or 11 on rst throw player wins 2 3 or 12 on first throw player loses 4 5 6 8 9 10 value becomes player39s quotpointquot 7 Player must roll his point before rolling 7 to W1n 7 Player loses if he rolls 7 before rolling his point 2mm Premise Hall In All ngms reserved Outline 1 rollDice prototype 12 Seed srand 2 Define switch statement for winlosscontinue 21 Loop
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'