ebook img

Programming in C 2/e PDF

574 Pages·2011·12.543 MB·English
by  DeyPradipGhoshManas
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Programming in C 2/e

Programming in   C  Second Edition          Pradip Dey   Manas Ghosh                        OXFORD  UNIVERSITY PRESS © Oxford University Press 2011  ISBN: 978-0-198065-28-9 C Preface to the First Edition Since the evolution of computers, a variety of program- CONTENT AND STRUCTURE ming languages have come into existence. C stands Chapter 1 begins by explaining the concept of program- out among general-purpose programming languages ming. It discusses the techniques of forming an organized for its unrivaled mix of portability, fl exibility, and ef- approach to problem solving. It also identifi es the differ- fi ciency. It is a versatile language and is commonly used ent types of programs and the various categories of pro- for developing application and system programs. C has gramming languages available. The prescribed tools that block structures, stand-alone functions, a compact set of are used in this process are described and explained with keywords, and very few restrictions. For all these rea- suffi cient examples and diagrams. sons, learning and using C is a necessity for most pro- For a beginner, Chapter 2 is undoubtedly the most im- grammers. portant chapter that describes the basic elements of C. This chapter introduces the keywords, the basic data types and ABOUT THE BOOK their modifi ers, operators and their precedence, and ex- This book is intended for an introductory course on pro- pressions and data type conversion rules. The basic struc- gramming in C. It assumes no prior programming expe- ture of a C program along with the common commands rience in C or any other language. Readers will fi nd the used in MS-DOS and UNIX/Linux for compiling and running explanations lucid and effective. Every feature of C has it has been described at length in this chapter. been demonstrated with appropriate programs tested and Accepting data from and conveying the results to a user run on a computer. The output obtained after executing is one of the most important actions desired from a pro- these programs have also been included. The explana- gram. To satisfy these requirements through the console, tions have been depicted with suitable diagrams to convey there are some commonly used input and output func- the concepts more effectively. Readers will be profi cient tions in C. These have been explained with illustrations in at programming after solving the review questions and Chapter 3. programming exercises given at the end of each chapter. Program fl ow control and looping constructs in C are ex- Though every attempt has been made to avoid and check plained in Chapter 4. The general statement format with fl ow- errors, we will be grateful to readers if they can bring charts and examples illustrate their signifi cance in programs. to our notice any errors that may have crept in inadver- Arrays and strings are two important data structures for tently. handling a cluster of homogeneous data. How such clus- vi Preface to the First Edition ters are declared and handled is explained with ample ex- The appendices contain case studies where the problem amples in Chapter 5. is fi rst defi ned and then the algorithm is developed, based The concept of functions, its form, and its requirement on which the C program is coded. Some sample runs ob- in a program is discussed in Chapter 6 with well-explained tained during the execution of these programs have also examples. Recursive functions are also described with been included. It also contains tables for ASCII codes, num- several examples. Analysis of time and space complexity ber system conversions, escape sequences, operators, data for an algorithm has also been presented in this chapter. types and data conversion rules, commonly used conver- One of the most important features of C is pointers. sion characters, and format tags. Among many other useful Starting with an introduction to pointers, Chapter 7 also topics covered in the appendices, an exhaustive listing of elaborates on how pointers are used with arrays, strings, C library functions, with programs illustrating how these and functions. The use of pointers is also described in functions can be put to use, have also been presented. depth with innumerable examples. User-defi ned data types such as structures and unions ACKNOWLEDGEMENTS are described in Chapter 8. What these data types com- We thank our students Rakesh Dutta and Niloy Debnath prise and how these are handled and used are illustrated for verifying the programs in this book and Sonia Khed- with examples. wal, Priyanka Nawalkar, Sayantani Saha, and Debolina Creating, amending, appending, and many other opera- Sharangi for their assistance in the preparation of the tions on fi les in C is a necessity for storing and retrieving model questions. We are grateful to the staff of Oxford data and programs. This has been covered in Chapter 9 University Press for their continuous cooperation, interest, with suffi cient examples. and assistance extended to us during the preparation of the Linked list, which is a popular data structure, has been book. We are also thankful to our colleague Mr Manash covered in Chapter 10. Various types of linked lists and the Sinharoy for helping us in preparing the manuscript in different operations that can be carried out on such linked time and Mr Tapas Kumar Tunga and Mr P.N. Pathak for lists have been discussed. In this chapter, readers will also their assistance in the preparation of the manuscript. get to know how pointers are used in constructing this data Special thanks are due to Mr Steve Summit for his ar- structure. ticles on C, which have guided us in preparing some of the Chapter 11 highlights some of the advanced features topics in this book. We also wish to thank Mr Vijay Kumar of C such as command-line arguments, bit-wise operators, R Zanvar and Mr Jayasima Ananth for the article on point- different memory models, and type qualifi ers with several ers and arrays as also Mr Thomas Jenkins for the article on illustrations. recursion, both of which have served as a guide during the Frequently asked questions are always a source of development of this manuscript. We express our gratitude learning. Some frequently asked questions have been in- to Mr Peter Burden, Mr Mike Banahan, Mr Declan Brady, cluded at end of the book, which will help readers to clear and Mr Mark Doran for their articles on C. any doubts pertaining to programming in C. PRADIP DEY MANAS GHOSH C Preface to the Second Edition Evolution of ideas is a never-ending process. New tech- ∑ Chapter-end case studies nology and changing needs have a tremendous infl uence ∑ Points to Note, Key Terms with defi nitions, Frequently on computing requirements, which in turn lead to continu- Asked Questions, and Project Questions with each ous enhancements of the power and scope of a program- chapter ming language. ∑ Improved explanations of algorithms and codes, and C99 is the modern standard of the C programming lan- new in-text examples guage. It extends the previous version (C90) with new lan- ∑ Incremental problem running through Ch 3 to 9, guage and library features, and helps programmers make bet- illustrating program code building from basics ter use of available computer hardware and compiler technol- ogy. The new features include inline functions, several new ∑ New sections such as variable length arrays, searching data types, and new header fi les. Hence, with the new fea- and sorting algorithms, pointer and const qualifi er, tures suggested by the C99 committee, the C programming and applications of linked lists language has expanded its scope and range of applications. ∑ Includes a CD that contains all the example programs, Accordingly, this edition offers several new topics, incremental problems, and case studies in a user- features based on the recommendations proposed by C99 friendly format. committee in relevant chapters, and many other useful fea- tures. A special effort has been made to simplify the exist- EXTENDED CHAPTER MATERIAL ing text with better treatment and explain the concepts with the help of examples containing appropriate comments. Chapter 1: Introduction to Programming: Further, the inclusion of key terms with brief defi nitions, Algorithms and Flowcharts FAQs with answers, and case studies demonstrating the stepwise approach of solving practical problems will aid Includes new sections on the reader to grasp the essence of the concepts and under- ∑ Correctness and termination of algorithms stand their practical implementation. ∑ Subroutines ∑ Strategy for designing algorithms NEW TO THE SECOND EDITION ∑ Tracing an algorithm to depict logic ∑ C99 features highlighted wherever relevant in the text ∑ Specifi cation for converting algorithms into ∑ New chapter on Stacks, Queues, and Trees programs iv Preface to the Second Edition Chapter 2: Basics of C Chapter 10: Linked Lists Includes new sections on New discussions on the stringizing operator, token pasting operator, and the optional third command line argument of ∑ Compilation model of a C program main() function have been included in this chapter. ∑ Philosophy of main() function ∑ The concept of Type qualifi ers Chapter 12: Stacks, Queues, and Trees ∑ How integers are stored in memory? It is a new chapter in this edition. This chapter explains the implementation of stacks and queues using arrays and Chapter 4: Control Statements linked lists as well as the applications of these two data Contains new sections on different forms of loop and mov- structures. It also explains binary trees, their traversal, ing out from a nested loop. types, and applications. Chapter 6: Functions ACKNOWLEDGEMENTS Includes new sections on We are grateful to a host of readers, who have encouraged ∑ Scope, storage class, and linkages us in improving this book by their useful suggestions from ∑ inline function time to time. There are no words to express our gratitude to Oxford University Press for their continuous support, ∑ Different sorting and searching methods along with suggestions, and assistance while preparing this edition. the analysis of time and space complexity Despite our best endeavour to make this edition error free, some may have crept in inadvertently. Comments and sugges- Chapter 7: Pointers tions for the improvement of the book are welcome. Please Includes new sections on send them to the publisher by logging on to their website www. ∑ Pointer and const qualifi er oup.com or to the authors at [email protected]. ∑ Constant parameter PRADIP DEY ∑ Returning pointer from a function MANAS GHOSH C Brief Contents Preface to the Second Edition ....................................................................................................................iiiiii Preface to the First Edition ..........................................................................................................................v 1. Introduction to Programming, Algorithms and Flowcharts ..............................................................1 2. Basics of C ......................................................................................................................................39 3. Input and Output ..............................................................................................................................94 4. Control Statements .........................................................................................................................117 5. Arrays and Strings ..........................................................................................................................169 6. Functions ........................................................................................................................................214 7. Pointers in C ...................................................................................................................................268 8. User-defi ned Data Types and Variables .........................................................................................350 9. Files in C ........................................................................................................................................388 10. Linked Lists ...................................................................................................................................423 11. Advanced C ....................................................................................................................................460 12. Stacks, Queues, and Trees ..............................................................................................................492 Appendices ...............................................................................................................................................524 Bibliography and References ...................................................................................................................544 Index ........................................................................................................................................................545 C Contents Preface to the Second Edition iii Preface to the First Edition v 1 INTRODUCTION TO PROGRAMMING, Modular Programming 12 ALGORITHMS AND FLOWCHARTS 1 Structured Code 13 The Process of Programming 13 1.1 Programs and Programming 1 1.9 Algorithms 14 System Software 2 What is an Algorithm? 14 Application Software 2 Different Ways of Stating Algorithms 14 1.2 Programming Languages 2 Key Features of an Algorithm and the Step- System Programming Languages 3 form 14 Application Programming Languages 3 What are Variables? 16 Low-level Languages 3 Subroutines 17 High-level Languages 5 Strategy for Designing Algorithms 30 1.3 Compiler, Interpreter, Loader, and Linker 6 Tracing an Algorithm to Depict Logic 31 Compiling and Executing High-level Language Specifi cation for Converting Algorithms into Programs 6 Programs 32 Linker 7 Loader 7 2 BASICS OF C 39 Linking Loader and Linkage Editor 8 2.1 Introduction 39 1.4 Program Execution 8 Why Learn C? 40 1.5 Fourth Generation Languages 9 The Future of C 40 1.6 Fifth Generation Languages 10 2.2 Standardizations of C Language 40 1.7 Classifi cation of Programming 10 2.3 Developing Programs In C 41 Procedural Languages 10 2.4 A Simple C Program 45 Problem-oriented Languages 11 2.5 Parts of C Program Revisited 47 Non-procedural Languages 11 2.6 Structure of a C Program 48 1.8 Structured Programming Concept 11 2.7 Concept of a Variable 49 Top–down Analysis 12 x Contents 2.8 Data Types in C 50 4.3 Writing Test Expression 119 2.9 Program Statement 55 Understanding How True and False is Represented 2.10 Declaration 56 in C 120 2.11 How Does The Computer Store Data in 4.4 Conditional Execution and Selection 124 Memory? 57 Selection Statements 124 How Integers are Stored? 57 The Conditional Operator 131 How Floats and Doubles are Stored? 58 The Switch Statement 133 2.12 Token 60 4.5 Iteration and Repetitive Execution 137 Identifi er 60 While Construct 138 Keywords 61 For Construct 143 Constant 61 do-while Construct 151 Assignment 63 4.6 Which Loop Should be Used? 153 Initialization 64 Using Sentinel Values 153 2.13 Operators and Expressions 65 Using Prime Read 154 Arithmetic Operators in C 66 Using Counter 155 Relational Operators in C 71 4.7 Goto Statement 155 Logical Operators in C 71 4.8 Special Control Statements 156 Bitwise Operators in C 72 4.9 Nested Loops 159 Conditional Operator in C 73 Comma Operator 73 Sizeof Operator 74 5 ARRAYS AND STRINGS 169 Expression Evaluation—Precedence and 5.1 Introduction 169 Associativity 74 5.2 One-Dimensional Array 170 2.14 Expressions Revisited 77 Declaration of a One-dimensional Array 171 2.15 Lvalues and Rvalues 77 Initializing Integer Arrays 173 2.16 Type Conversion in C 78 Accessing Array Elements 173 Type Conversion in Expressions 78 Other Allowed Operations 174 Conversion by Assignment 79 Internal Representation of Arrays in C 176 Casting Arithmetic Expressions 81 Variable Length Arrays and the C99 changes 177 2.17 Working with Complex Numbers 86 Working with One-dimensional Array 177 5.3 Strings: One-dimensional Character Arrays 182 3 INPUT AND OUTPUT 94 Declaration of a String 182 String Initialization 182 3.1 Introduction 94 Printing Strings 183 3.2 Basic Screen and Keyboard I/O in C 95 String Input 184 3.3 Non-Formatted Input and Output 96 Character Manipulation in the String 190 Single Character Input and Output 96 String Manipulation 191 Single Character Input 96 5.4 Multidimensional Arrays 199 Single Character Output 96 Declaration of a Two-dimensional Array 199 Additional Single Character Input and Output Functions 97 Declaration of a Three-dimensional Array 199 3.4 Formatted Input and Output Functions 100 Initialization of a Multidimensional Array 199 Output Function printf ( ) 100 Unsized Array Initializations 201 Input Function scanf ( ) 106 Accessing Multidimensional Arrays 201 Working with Two-dimensional Arrays 202 5.5 Arrays of Strings: Two-dimensional Character 4 CONTROL STATEMENTS 117 Array 206 4.1 Introduction 117 Initialization 206 4.2 Specifying Test Condition Forselection and Manipulating String Arrays 206 Iteration 119 Contents xi 6 FUNCTIONS 214 7.9 Pointers and Strings 288 7.10 Pointer Arithmetic 289 6.1 Introduction 214 Assignment 290 6.2 Concept of Function 215 Addition or Subtraction with Integers 291 Why are Functions Needed? 215 Subtraction of Pointers 298 6.3 Using Functions 216 Comparing Pointers 299 Function Prototype Declaration 216 7.11 Pointers to Pointers 300 Function Defi nition 217 7.12 Array of Pointers 302 Function Calling 219 7.13 Pointers To an Array 306 6.4 Call by Value Mechanism 221 7.14 Two-dimensional Arrays and Pointers 307 6.5 Working with Functions 221 Passing Two-dimensional Array to a Function 309 6.6 Passing Arrays to Functions 224 7.15 Three-dimensional Arrays 316 6.7 Scope and Extent 227 7.16 Pointers to Functions 317 Concept of Global and Local Variables 227 Declaration of a Pointer to a Function 317 Scope Rules 229 Initialization of Function Pointers 317 6.8 Storage Classes 231 Calling a Function using a Function Pointer 317 Storage Class Specifi ers for Variables 231 Passing a Function to another Function 318 Storage Class Specifi ers for Functions 234 How to Return a Function Pointer 319 Linkage 234 Arrays of Function Pointers 320 6.9 The Inline Function 234 7.17 Dynamic Memory Allocation 320 6.10 Recursion 235 Dynamic Allocation of Arrays 323 What is Needed for Implementing Recursion? 235 Freeing Memory 325 How is Recursion Implemented? 239 Reallocating Memory Blocks 327 Comparing Recursion and Iteration 241 Implementing Multidimensional Arraysusing 6.11 Searching and Sorting 241 Pointers 328 Searching Algorithms 241 7.18 Offsetting a Pointer 331 Sorting Algorithms 243 7.19 Memory Leak and Memory Corruption 333 6.12 Analysis of Algorithms 248 7.20 Pointer and Const Qualifi er 334 Asymptotic Notation 250 Pointer to Constant 334 Effi ciency of Linear Search 252 Constant Pointers 335 Binary Search Analysis 253 Constant Parameters 335 Analysis of Bubble Sort 254 Analysis of Quick Sort 255 Disadvantages of Complexity Analysis 255 8 USER-DEFINED DATA TYPES AND VARIABLES 350 7 POINTERS IN C 268 8.1 Introduction 350 8.2 Structures 351 7.1 Introduction 268 Declaring Structures and Structure Variables 351 7.2 Understanding Memory Addresses 269 Accessing the Members of a Structure 354 7.3 Address Operator (&) 271 Initialization of Structures 355 7.4 Pointer 272 Copying and Comparing Structures 359 Declaring a Pointer 272 Typedef and its Use in Structure Declarations 361 Initializing Pointers 274 Nesting of Structures 362 Indirection Operator and Dereferencing 276 Arrays of Structures 363 7.5 Void Pointer 278 Initializing Arrays of Structures 364 7.6 Null Pointer 278 Arrays within the Structure 365 7.7 Use of Pointers 279 Structures and Pointers 365 7.8 Arrays and Pointers 282 Structures and Functions 367 One-dimensional Arrays and Pointers 282 8.3 Union 370 Passing an Array to a Function 285 Declaring a Union and its Members 370 Differences Between Array Name and Pointer 286

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.