Let Us C (14th Ed.) (Yashavant Kanetkar) (Z-Library)

Author: Yashavant Kanetkar

科学

No Description

📄 File Format: PDF
💾 File Size: 17.7 MB
36
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
i Let Us C Fourteenth Edition Yashavant Kanetkar
📄 Page 3
ii Dedicated to baba Who couldn’t be here to see this day...
📄 Page 4
iii About the Author Through his books and Quest Video Courseware DVDs on C, C++, Data Structures, VC++, .NET, Embedded Systems, etc. Yashavant Kanetkar has created, moulded and groomed lacs of IT careers in the last two decades. Yashavant’s books and Quest DVDs have made a significant contribution in creating top-notch IT manpower in India and abroad. Yashavant’s books are globally recognized and millions of students / professionals have benefitted from them. Yashavant's books have been translated into Hindi, Gujarati, Japanese, Korean and Chinese languages. Many of his books are published in India, USA, Japan, Singapore, Korea and China. Yashavant is a much sought after speaker in the IT field and has conducted seminars/workshops at TedEx, IITs, RECs and global software companies. Yashavant has recently been honored with the prestigious “Distinguished Alumnus Award” by IIT Kanpur for his entrepreneurial, professional and academic excellence. This award was given to top 50 alumni of IIT Kanpur who have made significant contribution towards their profession and betterment of society in the last 50 years. In recognition of his immense contribution to IT education in India, he has been awarded the "Best .NET Technical Contributor" and "Most Valuable Professional" awards by Microsoft for 5 successive years. Yashavant holds a BE from VJTI Mumbai and M.Tech. from IIT Kanpur.
📄 Page 5
iv Acknowledgments Let Us C has become an important part of my life. I have created and nurtured it for last decade and half. While doing so, I have received, in addition to the compliments, a lot of suggestions from students, developers, professors, publishers and authors. So much have their inputs helped me in taking this book up to its fourteenth edition that ideally I should put their names too on the cover page. In particular, I am indebted to Manish Jain who had a faith in this book idea, believed in my writing ability, whispered the words of encouragement and made helpful suggestions from time to time. I hope every author gets a publisher who is as cooperative, knowledgeable and supportive as Manish. The Fourteen editions of this book saw several changes and facelifts. During this course many people helped in executing programs and spotting bugs. I trust that with their collective acumen, all the programs in this book would run correctly. I value the work that they did a lot. Any errors, omissions or inconsistencies that remain are, alas, my responsibility. I thank Dada, Ammi—my parents, Seema—my wife, Aditya, Anuj—my sons for enduring the late nights, the clicking keyboard, and mostly for putting up with yet another marathon book effort. Thinking of a book cover idea is one thing, putting it into action is a different cup of tea. This edition’s cover idea has been implemented by Jayant. Many thanks to him. And finally my heartfelt gratitude to the countless students who made me look into every nook and cranny of C. I want to remain in their debt. It is only because of them that Let Us C is now published from India, Singapore, USA, Japan, Korea and China in multiple languages.
📄 Page 6
v Preface In this I have reorganized the contents of the book in a major way. After going through the thirteenth edition several times I decided to realign all the chapters in such a manner that if a C programming course is taught using Let Us C, it can roughly be finished in 23 lectures of one hour each, with one chapter's contents devoted to one lecture. I hope this would make the learning path trouble-free. Some end-of-chapter exercises in the book needed a second look to make them more practical. That also stands done now. Many readers told me that they have immensely benefitted from the inclusion of the chapter on Interview FAQs. I have improved this chapter further. The rationale behind this chapter is simple—ultimately all the readers of Let Us C sooner or later end up in an interview room where they are required to take questions on C programming. I now have a proof that this chapter has helped to make that journey smooth and fruitful. All the programs present in the book are available in source code form at www.kicit.com/books/letusc/sourcecode. You are free to download them, improve them, change them, do whatever with them. If you wish to get solutions for the Exercises in the book they are available in another book titled ‘Let Us C Solutions’. If you want some more problems for practice they are available in the book titled ‘Let Us C Workbook’. As usual, new editions of these two books have also been launched along with 14th edition of Let Us C. If you like ‘Let Us C’ and want to hear the complete video-recorded lectures created by me on C language (and other subjects like C++, VC++, C#, Java, .NET, Embedded Systems, etc.), then you can visit http://quest.ksetindia.com for more details. ‘Let Us C’ is as much your book as it is mine. So if you feel that I could have done certain job better than what I have, or you have any suggestions about what you would like to see in the next edition, please drop a line to bpbpublications@gmail.com. Countless Indians have relentlessly worked for close to two decades to successfully establish “India” as a software brand. At times, I take secret pleasure in seeing that a Let Us C has contributed in its own little way in shaping so many careers that have made the “India” brand acceptable.
📄 Page 7
vi Recently I was presented with “Distinguished Alumnus Award” by IIT Kanpur. It was great to figure in a list that contained Narayan Murthy, Chief Mentor, Infosys, Dr. D. Subbarao, former Governor, Reserve Bank of India, Dr. Rajeev Motwani of Stanford University, Prof. H. C. Verma, Mr. Som Mittal President of NASSCOM, Prof. Minwalla of Harvard University, Dr. Sanjay Dhande former Director of IIT Kanpur, Prof. Arvind and Prof. Sur of MIT USA and Prof. Ashok Jhunjhunwala of IIT Chennai. I think Let Us C amongst my other books has been primarily responsible for helping me get the “Distinguished Alumnus” award. What was a bit surprising was that almost all who were present knew about the book already and wanted to know from me what it takes to write a book that sells in millions of copies. My reply was—make an honest effort to make the reader understand what you have to say and keep it simple. I don’t know how convincing was this answer, but well, that is what I have been doing with this book in all its previous thirteen editions. I have followed the same principle with this edition too. All the best and happy programming! Yashavant Kanetkar
📄 Page 8
vii Contents 1. Getting Started 1 What is C? 2 Getting Started with C 3 The C Character Set 4 Constants, Variables and Keywords 4 Types of C Constants 5 Rules for Constructing Integer Constants 6 Rules for Constructing Real Constants 7 Rules for Constructing Character Constants 8 Types of C Variables 8 Rules for Constructing Variable Names 8 C Keywords 9 The First C Program 10 Form of a C Program 11 Comments in a C Program 11 What is main( )? 12 Variables and their Usage 13 printf( ) and its Purpose 14 Compilation and Execution 15 Receiving Input 15 Summary 17 Exercise 18 2. C Instructions 21 Types of Instructions 22 Type Declaration Instruction 22 Arithmetic Instruction 23 Integer and Float Conversions 26 Type Conversion in Assignments 27 Hierarchy of Operations 28 Associativity of Operators 31 Control Instructions 32 Summary 32 Exercise 33 3. Decision Control Instruction 39 Decisions! Decisions! 40 The if Statement 40 The Real Thing 44
📄 Page 9
viii Multiple Statements within if 45 The if-else Statement 47 Nested if-elses 49 Forms of if 50 Summary 51 Exercise 51 4. More Complex Decision Making 57 Use of Logical Operators 58 The else if Clause 61 The ! Operator 66 Hierarchy of Operators Revisited 66 A Word of Caution 67 The Conditional Operators 69 Summary 71 Exercise 71 5. Loop Control Instruction 81 Loops 82 The while Loop 82 Tips and Traps 85 More Operators 88 Summary 90 Exercise 90 6. More Complex Repetitions 95 The for Loop 96 Nesting of Loops 101 Multiple Initializations in the for Loop 102 The break Statement 102 The continue Statement 104 The do-while Loop 105 The Odd Loop 107 Summary 109 Exercise 110 7. Case Control Instruction 117 Decisions using switch 118 The Tips and Traps 121 switch versus if-else Ladder 126 The goto Keyword 126
📄 Page 10
ix Summary 129 Exercise 129 8. Functions 135 What is a Function? 136 Why use Functions? 142 Passing Values between Functions 143 Scope Rule of Functions 147 Order of Passing Arguments 148 Using Library Functions 149 One Dicey Issue 150 Return Type of Function 150 Summary 151 Exercise 151 9. Pointers 157 Call by Value and Call by Reference 158 An Introduction to Pointers 158 Pointer Notation 159 Back to Function Calls 164 Conclusions 167 Summary 167 Exercise 168 10. Recursion 173 Recursion 174 Recursion and Stack 178 Summary 181 Exercise 181 11. Data Types Revisited 183 Integers, long and short 184 Integers, signed and unsigned 186 Chars, signed and unsigned 187 Floats and Doubles 188 A Few More Issues… 191 Storage Classes in C 192 Automatic Storage Class 193 Register Storage Class 194 Static Storage Class 195 External Storage Class 198
📄 Page 11
x A Few Subtle Issues 201 Which to Use When 202 Summary 203 Exercise 204 12. The C Preprocessor 211 Features of C Preprocessor 212 Macro Expansion 212 Macros with Arguments 216 Macros versus Functions 220 File Inclusion 221 Conditional Compilation 223 #if and #elif Directives 226 Miscellaneous Directives 227 #undef Directive 227 #pragma Directive 227 The Build Process 230 Preprocessing 231 Compilation 231 Assembling 232 Linking 233 Loading 234 Summary 235 Exercise 235 13. Arrays 239 What are Arrays? 240 A Simple Program using Array 241 More on Arrays 244 Array Initialization 244 Array Elements in Memory 244 Bounds Checking 245 Passing Array Elements to a Function 245 Pointers and Arrays 247 Passing an Entire Array to a Function 254 The Real Thing 255 Summary 256 Exercise 257 14. Multidimensional Arrays 267 Two-Dimensional Arrays 268
📄 Page 12
xi Initializing a Two-Dimensional Array 269 Memory Map of a Two-Dimensional Array 270 Pointers and Two-Dimensional Arrays 271 Pointer to an Array 273 Passing 2-D Array to a Function 274 Array of Pointers 277 Three-Dimensional Array 279 Summary 281 Exercise 281 15. Strings 291 What are Strings 292 More about Strings 293 Pointers and Strings 297 Standard Library String Functions 298 strlen( ) 299 strcpy( ) 301 strcat( ) 304 strcmp( ) 305 Summary 306 Exercise 306 16. Handling Multiple Strings 311 Two-Dimensional Array of Characters 312 Array of Pointers to Strings 314 Limitation of Array of Pointers to Strings 317 Solution 318 Summary 319 Exercise 319 17. Structures 323 Why use Structures? 324 Declaring a Structure 326 Accessing Structure Elements 329 How Structure Elements are Stored? 329 Array of Structures 330 Additional Features of Structures 332 Uses of Structures 341 Summary 341 Exercise 342
📄 Page 13
xii 18. Console Input/Output 351 Types of I/O 352 Console I/O Functions 353 Formatted Console I/O Functions 353 sprintf( ) and sscanf( ) Functions 361 Unformatted Console I/O Functions 362 Summary 365 Exercise 365 19. File Input/Output 371 Data Organization 372 File Operations 372 Opening a File 373 Reading from a File 375 Trouble in Opening a File 375 Closing the File 377 Counting Characters, Tabs, Spaces, … 377 A File-Copy Program 378 Writing to a File 380 File Opening Modes 380 String (Line) I/O in Files 381 The Awkward Newline 383 Record I/O in Files 384 Text Files and Binary Files 387 Record I/O Revisited 389 Database Management 392 Low-Level File I/O 398 A Low-Level File-Copy Program 399 I/O under Windows 403 Summary 403 Exercise 404 20. More Issues In Input/Output 413 Using argc and argv 414 Detecting Errors in Reading/Writing 417 Standard I/O Devices 419 I/O Redirection 419 Redirecting the Output 420 Redirecting the Input 421 Both Ways at Once 422 Summary 423
📄 Page 14
xiii Exercise 423 21. Operations On Bits 425 Bit Numbering and Conversion 426 Bit Operations 429 One’s Complement Operator 431 Right Shift Operator 433 Left Shift Operator 436 Utility of Left Shift Operator 437 Bitwise AND Operator 438 Utility of AND Operator 439 Bitwise OR Operator 442 Bitwise XOR Operator 443 The showbits( ) Function 444 Bitwise Compound Assignment Operator 445 Summary 445 Exercise 446 22. Miscellaneous Features 451 Enumerated Data Type 452 Uses of Enumerated Data Type 453 Are Enums Necessary? 455 Renaming Data Types with typedef 456 Typecasting 457 Bit Fields 459 Pointers to Functions 461 Functions Returning Pointers 463 Functions with Variable Number of Arguments 465 Unions 468 Union of Structures 473 Utility of Unions 474 The volatile Qualifier 476 Summary 476 Exercise 477 23. C Under Linux 481 What is Linux? 482 C Programming Under Linux 483 The ‘Hello Linux’ Program 483 Processes 484 Parent and Child Processes 485
📄 Page 15
xiv More Processes 488 Zombies and Orphans 490 One Interesting Fact 492 Communication using Signals 492 Handling Multiple Signals 495 Blocking Signals 497 Event Driven Programming 500 Where do you go from here? 505 Summary 505 Exercise 506 24. Interview FAQs 509 Appendix A – Compilation and Execution 529 Appendix B – Precedence Table 537 Appendix C – Chasing the Bugs 541 Appendix D – ASCII Chart 549 Periodic Tests I to IV 555 Index 567
📄 Page 16
xv
📄 Page 17
(This page has no text content)
📄 Page 18
1 1 Getting Started  What is C?  Getting Started with C The C Character Set Constants, Variables and Keywords Types of C Constants Rules for Constructing Integer Constants Rules for Constructing Real Constants Rules for Constructing Character Constants Types of C Variables Rules for Constructing Variable Names C Keywords  The First C Program Form of a C Program Comments in a C Program What is main( )? Variables and their Usage printf( ) and its Purpose Compilation and Execution  Receiving Input  Summary  Exercise
📄 Page 19
2 Let Us C efore we can begin to write serious programs in C, it would be interesting to find out what really is C, how it came into existence and how does it compare with other programming languages. In this chapter, we would briefly outline these issues. Four important aspects of any language are the way it stores data, the way it operates upon this data, how it accomplishes input and output, and how it lets you control the sequence of execution of instructions in a program. We would discuss the first three of these building blocks in this chapter. What is C? C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL, etc. No one pushed C. It wasn’t made the ‘official’ Bell Labs language. Thus, without any advertisement, C’s reputation spread and its pool of users grew. Ritchie seems to have been rather surprised that so many programmers preferred C to older languages like FORTRAN or PL/I, or the newer ones like Pascal and APL. But, that’s what happened. Possibly why C seems so popular is because it is reliable, simple and easy to use. Moreover, in an industry where newer languages, tools and technologies emerge and vanish day in and day out, a language that has survived for more than three decades has to be really good. An opinion that is often heard today is—“C has been already superseded by languages like C++, C# and Java, so why bother to learn C today”. I seriously beg to differ with this opinion. There are several reasons for this. These are as follows: (a) C++, C# or Java make use of a principle called Object Oriented Programming (OOP) to organize the program. This organizing principle has lots of advantages to offer. But even while using this organizing principle you would still need a good hold over the language elements of C and the basic programming skills. So it makes more sense to first learn C and then migrate to C++, C# and Java. Though this two-step learning process may take more time, but at the end of it you will definitely find it worth the trouble. (b) Major parts of popular operating systems like Windows, UNIX, Linux and Android are written in C. This is because even today when it B
📄 Page 20
Chapter 1: Getting Started 3 comes to performance (speed of execution) nothing beats C. Moreover, if one is to extend the operating system to work with new devices one needs to write device driver programs. These programs are exclusively written in C. (c) Mobile devices like Smartphones and Tablets have become rage of today. Also, common consumer devices like microwave ovens, washing machines and digital cameras are getting smarter by the day. This smartness comes from a microprocessor, an operating system and a program embedded in these devices. These programs not only have to run fast but also have to work in limited amount of memory. No wonder that such programs are written in C. With these constraints on time and space, C is the language of choice while building such operating systems and programs. (d) You must have seen several professional 3D computer games where the user navigates some object, like say a spaceship and fires bullets at the invaders. The essence of all such games is speed. Needless to say, such games won’t become popular if they take a long time to move the spaceship or to fire a bullet. To match the expectations of the player the game has to react fast to the user inputs. This is where C language scores over other languages. Many popular gaming frameworks (like DirectX) have been built using C language. (e) At times one is required to very closely interact with the hardware devices. Since C provides several language elements that make this interaction feasible without compromising the performance, it is the preferred choice of the programmer. I hope that these are very convincing reasons why you should adopt C as the first, and a very important step, in your quest for learning programming. Getting Started with C Communicating with a computer involves speaking the language the computer understands, which immediately rules out English as the language of communication with computer. However, there is a close analogy between learning English language and learning C language. The classical method of learning English is to first learn the alphabets used in the language, then learn to combine these alphabets to form words, which, in turn, are combined to form sentences and sentences are combined to form paragraphs.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List