C: From Theory to Practice Second Edition George S. Tselikis Nikolaos D. Tselikas CRC Press Taylor & Francis Group 6000 Broken Sound Parkway NW, Suite 300 Boca Raton, FL 33487-2742 © 2017 by Taylor & Francis Group, LLC CRC Press is an imprint of Taylor & Francis Group, an Informa business International Standard Book Number-13: 978-1-138-63600-2 (Hardback) Visit the Taylor & Francis Web site at http://www.taylorandfrancis.com and the CRC Press Web site at http://www.crcpress.com Contents Preface .............................................................................................................................................xv Acknowledgments .....................................................................................................................xvii About the Authors ......................................................................................................................xix 1. Introduction to C.....................................................................................................................1 History of C ..............................................................................................................................1 The ANSI Standard .................................................................................................................1 Advantages of C .......................................................................................................................2 Disadvantages of C ..................................................................................................................2 C Program Life Cycle ..............................................................................................................3 Writing a C Program ...............................................................................................................3 Our First C Program ................................................................................................................3 The #include Directive ....................................................................................................3 The main() Function .........................................................................................................4 Comments ............................................................................................................................5 Compilation ..............................................................................................................................6 Common Errors ...................................................................................................................7 Linking ......................................................................................................................................7 Run the Program ......................................................................................................................8 2. Data Types, Variables, and Data Output ...........................................................................9 Variables ....................................................................................................................................9 Naming Variables ....................................................................................................................9 Declaring Variables ...............................................................................................................10 Assignment of Values and Constants .................................................................................13 Arithmetic Conversions ........................................................................................................15 Type Qualifiers .......................................................................................................................18 The #define Directive .........................................................................................................19 The printf() Function ........................................................................................................20 Escape Sequences ..............................................................................................................20 Conversion Specifications ................................................................................................22 Return Value ......................................................................................................................23 Printing Variables .............................................................................................................24 Optional Fields ..................................................................................................................25 Precision ........................................................................................................................25 Field Width ....................................................................................................................27 Prefix ..............................................................................................................................27 Flags ...............................................................................................................................28 Exercises ..................................................................................................................................29 Unsolved Exercises ................................................................................................................31 3. Getting Input with scanf() ..................................................................................................35 The scanf() Function ..........................................................................................................35 Use of Ordinary Characters ............................................................................................37 Return Value ......................................................................................................................38 Exercises ..................................................................................................................................39 Unsolved Exercises ................................................................................................................43 4. Operators ................................................................................................................................45 The = Assignment Operator .................................................................................................45 Arithmetic Operators ............................................................................................................46 The ++ and -- Operators ......................................................................................................47 Relational Operators ..............................................................................................................49 Exercises ..................................................................................................................................50 Compound Assignment Operators .....................................................................................50 Logical Operators...................................................................................................................51 The ! Operator ..................................................................................................................52 The && Operator ................................................................................................................52 The || Operator .................................................................................................................53 Exercises ..................................................................................................................................53 The Comma Operator ...........................................................................................................56 The sizeof Operator ............................................................................................................57 The enum Type .......................................................................................................................59 Bitwise Operators ..................................................................................................................60 The & Operator ..................................................................................................................61 The | Operator ..................................................................................................................61 The ^ Operator ..................................................................................................................61 The ~ Operator ..................................................................................................................62 Shift Operators ..................................................................................................................62 Exercises ..................................................................................................................................63 Operator Precedence .............................................................................................................70 Unsolved Exercises ................................................................................................................71 5. Program Control ...................................................................................................................73 The if Statement ...................................................................................................................73 Common Errors .................................................................................................................74 The if-else Statement .........................................................................................................75 Nested if Statements ............................................................................................................76 Exercises ..................................................................................................................................79 The Conditional Operator ?: ...............................................................................................88 Exercises ..................................................................................................................................90 The switch Statement ..........................................................................................................92 switch versus if ..................................................................................................................96 Exercises ..................................................................................................................................96 Unsolved Exercises ..............................................................................................................100 6. Loops .....................................................................................................................................105 The for Statement ...............................................................................................................105 Omitting Expressions .....................................................................................................108 Exercises ................................................................................................................................109 The break Statement ..........................................................................................................111 The continue Statement ...................................................................................................113 Exercises ................................................................................................................................114 Nested Loops ........................................................................................................................124 Exercises ................................................................................................................................126 The while Statement ..........................................................................................................129 Exercises ................................................................................................................................132 The do-while Statement ...................................................................................................140 Exercises ................................................................................................................................141 The goto Statement .............................................................................................................144 Unsolved Exercises ..............................................................................................................145 7. Arrays ....................................................................................................................................151 One-Dimensional Arrays ....................................................................................................151 Declaring Arrays .............................................................................................................151 Accessing Array Elements .............................................................................................152 Array Initialization .........................................................................................................154 Exercises ................................................................................................................................155 Two-Dimensional Arrays ....................................................................................................170 Declaring Arrays .............................................................................................................170 Accessing Array Elements .............................................................................................171 Array Initialization .........................................................................................................172 Exercises ................................................................................................................................174 Unsolved Exercises ..............................................................................................................184 8. Pointers .................................................................................................................................187 Pointers and Memory ..........................................................................................................187 Pointer Declaration ..............................................................................................................187 Pointer Initialization ............................................................................................................189 Null Pointers .........................................................................................................................189 Using a Pointer .....................................................................................................................190 Exercises ................................................................................................................................192 The void* Pointer ...............................................................................................................197 Use of const Qualifier .......................................................................................................198 Pointer Arithmetic ...............................................................................................................199 Pointers and Integers ......................................................................................................199 Subtracting and Comparing Pointers ..........................................................................201 Exercises ................................................................................................................................201 Pointers and Arrays .............................................................................................................203 Exercises ................................................................................................................................207 Array of Pointers ..................................................................................................................216 Exercises ................................................................................................................................218 Pointer to Pointer .................................................................................................................219 Exercises ................................................................................................................................220 Pointers and Two-Dimensional Arrays ............................................................................222 Exercises ................................................................................................................................225 Pointer to Function ..............................................................................................................228 Array of Pointers to Functions ...........................................................................................231 Unsolved Exercises ..............................................................................................................235 9. Characters .............................................................................................................................239 The char Type .....................................................................................................................239 Exercises ................................................................................................................................242 The getchar() and putchar() Functions....................................................................245 Exercises ................................................................................................................................246 10. Strings ...................................................................................................................................253 String Literals .......................................................................................................................253 Storing Strings ......................................................................................................................253 Exercise ..................................................................................................................................254 Writing Strings .....................................................................................................................255 Exercises ................................................................................................................................257 Pointers and String Literals ................................................................................................258 Exercises ................................................................................................................................260 Read Strings ..........................................................................................................................261 Exercises ................................................................................................................................264 String Functions ...................................................................................................................270 The strlen() Function .................................................................................................270 Exercises ................................................................................................................................270 The strcpy() and strncpy() Functions .................................................................278 Exercises ................................................................................................................................280 The strcat() Function .................................................................................................282 The strcmp() and strncmp() Functions .................................................................284 Exercises ................................................................................................................................285 Two-Dimensional Arrays and Strings ..............................................................................292 Exercises ................................................................................................................................293 Unsolved Exercises ..............................................................................................................295 11. Functions ..............................................................................................................................299 Function Declaration ...........................................................................................................299 Return Value ....................................................................................................................299 Function Parameters .......................................................................................................300 Function Definition .............................................................................................................300 Complex Declarations .........................................................................................................303 The return Statement ........................................................................................................304 Function Call ........................................................................................................................305 Function Call without Parameters ................................................................................305 Function Call with Parameters .....................................................................................307 Exercises ................................................................................................................................311 Storage Classes and Variables Scope .................................................................................321 Local Variables.................................................................................................................322 Global Variables...............................................................................................................325 Static Variables .................................................................................................................327 One-Dimensional Array as Argument .............................................................................330 Exercises ................................................................................................................................336 Two-Dimensional Array as Argument .............................................................................358 Exercises ................................................................................................................................359 Passing Data in main() Function .....................................................................................364 Exercises ................................................................................................................................365 Functions with Variable Number of Parameters .............................................................366 Exercise ..................................................................................................................................368 Recursive Functions ............................................................................................................369 Exercises ................................................................................................................................371 Unsolved Exercises ..............................................................................................................376 12. Searching and Sorting Arrays .........................................................................................381 Searching Arrays .................................................................................................................381 Linear Search Algorithm ...............................................................................................381 Exercises ................................................................................................................................381 Binary Search Algorithm ...............................................................................................383 Exercises ................................................................................................................................384 Sorting Arrays ......................................................................................................................386 Selection Sort Algorithm ................................................................................................386 Exercises ................................................................................................................................387 Insertion Sort Algorithm ...............................................................................................392 Exercise ..................................................................................................................................393 Bubble Sort Algorithm ...................................................................................................395 Exercises ................................................................................................................................395 Quick Sort Algorithm .....................................................................................................398 The bsearch() and qsort() Library Functions ..........................................................400 Exercise ..................................................................................................................................401 Unsolved Exercises ..............................................................................................................402 13. Structures and Unions .......................................................................................................405 Structures ..............................................................................................................................405 Declare a Structure .........................................................................................................405 The typedef Specifier ...................................................................................................408 Initializing a Structure ...................................................................................................410 Pointer to a Structure Member ......................................................................................412 Structure Operations ......................................................................................................413 Structure Containing Arrays .........................................................................................414 Structure Containing Pointers ......................................................................................415 Nested Structures............................................................................................................415 Bit Fields ...........................................................................................................................417 Pointer to Structure .........................................................................................................419 Array of Structures .........................................................................................................420 Exercises ................................................................................................................................422 Structure as Function Argument ..................................................................................424 Exercises ................................................................................................................................426 Unions....................................................................................................................................437 Union Declaration ...........................................................................................................437 Access Union Members ..................................................................................................438 Exercise ..................................................................................................................................443 Unsolved Exercises ..............................................................................................................445 14. Memory Management and Data Structures ..................................................................449 Memory Blocks .....................................................................................................................449 Static Memory Allocation ...................................................................................................450 Dynamic Memory Allocation ............................................................................................451 The malloc() Function .................................................................................................452 The free() Function .....................................................................................................455 Memory Management Functions ......................................................................................458 Exercises ................................................................................................................................460 Dynamic Data Structures ...................................................................................................471 Linked List ............................................................................................................................471 Insert a Node ...................................................................................................................472 Delete a Node ..................................................................................................................472 Implementation Examples ..................................................................................................473 Implementing a Stack .....................................................................................................473 Exercise ..................................................................................................................................473 Implementing a Queue ...................................................................................................478 Exercise ..................................................................................................................................478 Implementing a Linked List ..........................................................................................481 Exercises ................................................................................................................................481 Binary Search Tree ...............................................................................................................488 Exercises ................................................................................................................................495 Hashing .................................................................................................................................497 Exercise ..................................................................................................................................500 Unsolved Exercises ..............................................................................................................501 15. Files ........................................................................................................................................507 Binary Files and Text Files ..................................................................................................507 Open a File ............................................................................................................................508 Close a File ............................................................................................................................510 Process a File ....................................................................................................................511 Write Data in a Text File ......................................................................................................511 The fputs() Function ...................................................................................................511 The fprintf() Function ...............................................................................................512 Exercise ..................................................................................................................................513 The fputc() Function ...................................................................................................514 Exercises ................................................................................................................................515 Read Data from a Text File .................................................................................................518 The fscanf() Function .................................................................................................518 Exercises ................................................................................................................................521 The fgets() Function ...................................................................................................523 Exercise ..................................................................................................................................525 The fgetc() Function ...................................................................................................526 Exercises ................................................................................................................................526 End of File .............................................................................................................................530 The fseek() and ftell() Functions ..............................................................................531 Write and Read Data from a Binary File ..........................................................................532 The fwrite() Function .................................................................................................532 The fread() Function ...................................................................................................533 Exercises ................................................................................................................................534 The feof() Function ..........................................................................................................544 Exercise ..................................................................................................................................545 Unsolved Exercises ..............................................................................................................545 16. The Preprocessor ................................................................................................................549 Simple Macros ......................................................................................................................549 Macros with Parameters .....................................................................................................554 # and ## Preprocessor Operators ......................................................................................556 Preprocessor Directives and Conditional Compilation .................................................557 The #if, #else, #elif, and #endif Directives .......................................................558 The #ifdef, #ifndef, and #undef Directives .........................................................560 The defined Operator ..................................................................................................561 Miscellaneous Directives ....................................................................................................562 Exercises ................................................................................................................................563 Unsolved Exercises ..............................................................................................................567 17. Building Large Programs ..................................................................................................571 18. Introduction to C++ ............................................................................................................579 Classes and Objects .............................................................................................................579 Constructors and Destructors ............................................................................................582 Overloading of Functions and Operators ........................................................................584 Inheritance ............................................................................................................................589 Polymorphism ......................................................................................................................594 Templates and Standard Template Library ......................................................................596 Function Templates .........................................................................................................596 Class Templates ...............................................................................................................599 Standard Template Library ............................................................................................600 More Features .......................................................................................................................602 The new and delete Operators ...................................................................................602 Reference Variables .........................................................................................................604 Exceptions ........................................................................................................................606 19. Introduction to Java ............................................................................................................611 Classes and Objects .............................................................................................................611 Packages ................................................................................................................................614 Constructors .........................................................................................................................614 Access Modifiers and Nonaccess Modifiers ....................................................................616 Inheritance ............................................................................................................................620 Polymorphism ......................................................................................................................623 Method Overloading ......................................................................................................624 Method Overriding .........................................................................................................625 Interfaces ...............................................................................................................................626 20. Review Exercises .................................................................................................................631 Appendix 1: Precedence Table .................................................................................................663 Appendix 2: ASCII Table .........................................................................................................665 Appendix 3: Library Functions ...............................................................................................667 Appendix 4: Hexadecimal System ..........................................................................................677 Index .............................................................................................................................................679 Preface This book is primarily addressed to students who are taking a course on the C language, to those who desire to pursue self-study of the C language, as well as to programmers already familiar with C who want to test their knowledge and skills. It could also prove useful to instructors of a C course who are looking for explanatory programming exam- ples to add in their lectures. So what exactly differentiates this book from the others in the field? This book tests the skills of both beginners and more experienced developers by providing an easy-to-read compilation of the C theory enriched with tips and advice as well as a large number of difficulty-scaled solved programming exercises. When we first encountered the C language as students, we needed a book that would introduce us quickly to the secrets of the C language as well as provide in-depth knowl- edge on the subject—a book with a focus on providing inside information and program- ming knowledge through practical examples and meaningful advice. That is the spirit that this book aims to capture. The programming examples are short but concrete, providing programming know-how in a substantial manner. Rest assured that if you are able to understand the examples and solve the exercises, you can safely go on to edit longer programs and start your program- ming career successfully. The source code of the exercises is available at www.c4all.gr. For all of you who intend to deal with computer programming, a little bit of advice com- ing from our long experience may come in handy: • Programming is a difficult task that, among other things, requires a calm mind, a clear development plan, a methodical approach, patience, self-confidence, and luck as well. • When coding, try to write in a simple and comprehensive way for your own ben- efit and for those who are going to read your code. Always remember that the debug, maintenance, and upgrade of a code written in a complex way are a pain- ful process. • Hands-on! To learn the features of any programming language, you must write your own programs and experiment with them. • Programming is definitely a creative activity, but do not forget that there are plenty of creative, pleasant, and less stressful activities in life. Do not waste your life in front of a computer screen, searching for losing pointers, buffer overflows, memory overruns, and buggy conditions. Program for some time and then have some fun. Keep living and do not keep programming. Enjoy the C flight; it will be safe, with some turbulence, though.
Description: