Teach Yourself C In 21 Days, Second Edition

2y ago
49 Views
2 Downloads
1.67 MB
772 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Allyson Cromer
Transcription

Teach Yourself C in 21 Days,Second EditionIntroductionWeek 1 at a Glance:Day 1 Getting StartedDay 2 The Parts of a C ProgramDay 3 Variables and ConstantsDay 4 Expressions and StatementsDay 5 FunctionsDay 6 Basic ClassesDay 7 More Program FlowWeek 1 in ReviewWeek 2 at a Glance:Day 8 PointersDay 9 ReferencesDay 10 Advanced FunctionsDay 11 Arrays

Day 12 InheritanceDay 13 PolymorphismDay 14 Special Classes and FunctionsWeek 2 in ReviewWeek 3 at a Glance:Day 15 Advanced InheritanceDay 16 StreamsDay 17 The PreprocessorDay 18 Object-Oriented Analysis and DesignDay 19 TemplatesDay 20 Exceptions and Error HandlingDay 21 Whats NextWeek 3 in ReviewAppendixesA Operator PrecedenceB C KeywordsC Binary and HexadecimalD Answers

Index

Teach YourselfC in 21 Days,Second EditionDedicationThis book is dedicated to the living memory of David Levine.AcknowledgmentsA second edition is a second chance to acknowledge and to thank those folks without whose supportand help this book literally would have been impossible. First among them are Stacey, Robin, andRachel Liberty.I must also thank everyone associated with my books, both at Sams and at Wrox press, for beingprofessionals of the highest quality. The editors at Sams did a fantastic job, and I must especiallyacknowledge and thank Fran Hatton, Mary Ann Abramson, Greg Guntle, and Chris Denny.I have taught an online course based on this book for a couple years, and many folks there contributedto finding and eradicating bugs and errors. A very large debt is owed to these folks, and I mustespecially thank Greg Newman, Corrinne Thompson, and also Katherine Prouty and JenniferGoldman.I would also like to acknowledge the folks who taught me how to program: Skip Gilbrech and DavidMcCune, and those who taught me C , including Steve Rogers and Stephen Zagieboylo. I wantparticularly to thank Mike Kraley, Ed Belove, Patrick Johnson, Mike Rothman, and Sangam Pant, allof whom taught me how to manage a project and ship a product.Others who contributed directly or indirectly to this book include: Scott Boag, David Bogartz, GeneBroadway, Drew and Al Carlson, Frank Childs, Jim Culbert, Thomas Dobbing, James Efstratiou,

David Heath, Eric Helliwell, Gisele and Ed Herlihy, Mushtaq Khalique, Matt Kingman, Steve Leland,Michael Smith, Frank Tino, Donovan White, Mark Woodbury, Wayne Wylupski, and Alan Zeitchek.Programming is as much a business and creative experience as it is a technical one, and I musttherefore acknowledge Tom Hottenstein, Jay Leve, David Rollert, David Shnaider, and RobertSpielvogel.Finally, I'd like to thank Mrs. Kalish, who taught my sixth-grade class how to do binary arithmetic in1965, when neither she nor we knew why.Tell Us What You Think!As a reader, you are the most important critic and commentator of our books. We value your opinionand want to know what we're doing right, what we could do better, what areas you'd like to see uspublish in, and any other words of wisdom you're willing to pass our way. You can help us makestrong books that meet your needs and give you the computer guidance you require.Do you have access to CompuServe or the World Wide Web? Then check out our CompuServe forumby typing GO SAMS at any prompt. If you prefer the World Wide Web, check out our site athttp://www.mcp.comNOTE: If you have a technical question about this book, call the technical support lineat 317-581-3833.As the publishing manager of the group that created this book, I welcome your comments. You canfax, e-mail, or write me directly to let me know what you did or didn't like about this book--as well aswhat we can do to make our books stronger. Here's the information:Fax: 317-581-4669E-mail: programming mgr@sams.mcp.comMail: Greg Wiegand Sams Publishing 201 W. 103rd Street Indianapolis, IN 46290IntroductionThis book is designed to help you teach yourself how to program with C . In just 21 days, you'lllearn about such fundamentals as managing I/O, loops and arrays, object-oriented programming,templates, and creating C applications--all in well-structured and easy-to-follow lessons. Lessonsprovide sample listings--complete with sample output and an analysis of the code--to illustrate thetopics of the day. Syntax examples are clearly marked for handy reference.

To help you become more proficient, each lesson ends with a set of common questions and answers,exercises, and a quiz. You can check your progress by examining the quiz and exercise answersprovided in the book's appendix.Who Should Read This BookYou don't need any previous experience in programming to learn C with this book. This book startsyou from the beginning and teaches you both the language and the concepts involved withprogramming C . You'll find the numerous examples of syntax and detailed analysis of code anexcellent guide as you begin your journey into this rewarding environment. Whether you are justbeginning or already have some experience programming, you will find that this book's clearorganization makes learning C fast and easy.ConventionsNOTE: These boxes highlight information that can make your C programming moreefficient and effective.WARNING: These focus your attention on problems or side effects that can occur inspecific situations.These boxes provide clear definitions of essential terms.DO use the "Do/Don't" boxes to find a quick summary of a fundamental principle in alesson. DON'T overlook the useful information offered in these boxes.This book uses various typefaces to help you distinguish C code from regular English. Actual C code is typeset in a special monospace font. Placeholders--words or characters temporarily used torepresent the real words or characters you would type in code--are typeset in italic monospace. Newor important terms are typeset in italic.In the listings in this book, each real code line is numbered. If you see an unnumbered line in a listing,you'll know that the unnumbered line is really a continuation of the preceding numbered code line(some code lines are too long for the width of the book). In this case, you should type the two lines asone; do not divide them.

Day 1 Getting Started Introduction A Brief History of C Programs Solving Problems Procedural, Structured, and Object-Oriented Programming C and Object-Oriented Programming How C Evolved The ANSI Standard Should I Learn C First? Preparing to Program Your Development Environment Compiling the Source Code Creating an Executable File with the Linker The Development Cycle Figure 1.1. HELLO.CPPYour First C Program Listing 1.1. HELLO.CPP, the Hello World program. Compile Errors Listing 1.2. Demonstration of compiler error. Summary Q&A Workshop Quiz ExercisesDay 1Getting StartedIntroduction

Welcome to Teach Yourself C in 21 Days! Today you will get started on your way to becoming aproficient C programmer. You'll learn Why C is the emerging standard in software development. The steps to develop a C program. How to enter, compile, and link your first working C program.A Brief History of C Computer languages have undergone dramatic evolution since the first electronic computers werebuilt to assist in telemetry calculations during World War II. Early on, programmers worked with themost primitive computer instructions: machine language. These instructions were represented by longstrings of ones and zeroes. Soon, assemblers were invented to map machine instructions to humanreadable and -manageable mnemonics, such as ADD and MOV.In time, higher-level languages evolved, such as BASIC and COBOL. These languages let peoplework with something approximating words and sentences, such as Let I 100. Theseinstructions were translated back into machine language by interpreters and compilers. An interpretertranslates a program as it reads it, turning the program instructions, or code, directly into actions. Acompiler translates the code into an intermediary form. This step is called compiling, and produces anobject file. The compiler then invokes a linker, which turns the object file into an executable program.Because interpreters read the code as it is written and execute the code on the spot, interpreters areeasy for the programmer to work with. Compilers, however, introduce the extra steps of compilingand linking the code, which is inconvenient. Compilers produce a program that is very fast each timeit is run. However, the time-consuming task of translating the source code into machine language hasalready been accomplished.Another advantage of many compiled languages like C is that you can distribute the executableprogram to people who don't have the compiler. With an interpretive language, you must have thelanguage to run the program.For many years, the principle goal of computer programmers was to write short pieces of code thatwould execute quickly. The program needed to be small, because memory was expensive, and itneeded to be fast, because processing power was also expensive. As computers have become smaller,cheaper, and faster, and as the cost of memory has fallen, these priorities have changed. Today thecost of a programmer's time far outweighs the cost of most of the computers in use by businesses.Well-written, easy-to-maintain code is at a premium. Easy- to-maintain means that as businessrequirements change, the program can be extended and enhanced without great expense.Programs

The word program is used in two ways: to describe individual instructions, or source code, created bythe programmer, and to describe an entire piece of executable software. This distinction can causeenormous confusion, so we will try to distinguish between the source code on one hand, and theexecutable on the other.New Term: A program can be defined as either a set of written instructions created by aprogrammer or an executable piece of software.Source code can be turned into an executable program in two ways: Interpreters translate the sourcecode into computer instructions, and the computer acts on those instructions immediately.Alternatively, compilers translate source code into a program, which you can run at a later time.While interpreters are easier to work with, most serious programming is done with compilers becausecompiled code runs much faster. C is a compiled language.Solving ProblemsThe problems programmers are asked to solve have been changing. Twenty years ago, programs werecreated to manage large amounts of raw data. The people writing the code and the people using theprogram were all computer professionals. Today, computers are in use by far more people, and mostknow very little about how computers and programs work. Computers are tools used by people whoare more interested in solving their business problems than struggling with the computer.Ironically, in order to become easier to use for this new audience, programs have become far moresophisticated. Gone are the days when users typed in cryptic commands at esoteric prompts, only tosee a stream of raw data. Today's programs use sophisticated "user-friendly interfaces," involvingmultiple windows, menus, dialog boxes, and the myriad of metaphors with which we've all becomefamiliar. The programs written to support this new approach are far more complex than those writtenjust ten years ago.As programming requirements have changed, both languages and the techniques used for writingprograms have evolved. While the complete history is fascinating, this book will focus on thetransformation from procedural programming to object-oriented programming.Procedural, Structured, and Object-Oriented ProgrammingUntil recently, programs were thought of as a series of procedures that acted upon data. A procedure,or function, is a set of specific instructions executed one after the other. The data was quite separatefrom the procedures, and the trick in programming was to keep track of which functions called whichother functions, and what data was changed. To make sense of this potentially confusing situation,structured programming was created.The principle idea behind structured programming is as simple as the idea of divide and conquer. Acomputer program can be thought of as consisting of a set of tasks. Any task that is too complex to be

described simply would be broken down into a set of smaller component tasks, until the tasks weresufficiently small and self-contained enough that they were easily understood.As an example, computing the average salary of every employee of a company is a rather complextask. You can, however, break it down into these subtasks:1. Find out what each person earns.2. Count how many people you have.3. Total all the salaries.4. Divide the total by the number of people you have.Totaling the salaries can be broken down into1. Get each employee's record.2. Access the salary.3. Add the salary to the running total.4. Get the next employee's record.In turn, obtaining each employee's record can be broken down into1. Open the file of employees.2. Go to the correct record.3. Read the data from disk.Structured programming remains an enormously successful approach for dealing with complexproblems. By the late 1980s, however, some of the deficiencies of structured programing had becameall too clear.First, it is natural to think of your data (employee records, for example) and what you can do withyour data (sort, edit, and so on) as related ideas.Second, programmers found themselves constantly reinventing new solutions to old problems. This isoften called "reinventing the wheel," and is the opposite of reusability. The idea behind reusability isto build components that have known properties, and then to be able to plug them into your programas you need them. This is modeled after the hardware world--when an engineer needs a new transistor,she doesn't usually invent one, she goes to the big bin of transistors and finds one that works the wayshe needs it to, or perhaps modifies it. There was no similar option for a software engineer.

New Term: The way we are now using computers--with menus and buttons and windows-fosters a more interactive, event-driven approach to computer programming. Event-drivenmeans that an event happens--the user presses a button or chooses from a menu--and theprogram must respond. Programs are becoming increasingly interactive, and it has becameimportant to design for that kind of functionality.Old-fashioned programs forced the user to proceed step-by-step through a series of screens. Modernevent-driven programs present all the choices at once and respond to the user's actions.Object-oriented programming attempts to respond to these needs, providing techniques for managingenormous complexity, achieving reuse of software components, and coupling data with the tasks thatmanipulate that data.The essence of object-oriented programming is to treat data and the procedures that act upon the dataas a single "object"--a self-contained entity with an identity and certain characteristics of its own.C and Object-Oriented ProgrammingC fully supports object-oriented programming, including the four pillars of object-orienteddevelopment: encapsulation, data hiding, inheritance, and polymorphism. Encapsulation and DataHiding When an engineer needs to add a resistor to the device she is creating, she doesn't typicallybuild a new one from scratch. She walks over to a bin of resistors, examines the colored bands thatindicate the properties, and picks the one she needs. The resistor is a "black box" as far as the engineeris concerned--she doesn't much care how it does its work as long as it conforms to her specifications;she doesn't need to look inside the box to use it in her design.The property of being a self-contained unit is called encapsulation. With encapsulation, we canaccomplish data hiding. Data hiding is the highly valued characteristic that an object can be usedwithout the user knowing or caring how it works internally. Just as you can use a refrigerator withoutknowing how the compressor works, you can use a well-designed object without knowing about itsinternal data members.Similarly, when the engineer uses the resistor, she need not know anything about the internal state ofthe resistor. All the properties of the resistor are encapsulated in the resistor object; they are not spreadout through the circuitry. It is not necessary to understand how the resistor works in order to use iteffectively. Its data is hidden inside the resistor's casing.C supports the properties of encapsulation and data hiding through the creation of user-definedtypes, called classes. You'll see how to create classes on Day 6, "Basic Classes." Once created, a welldefined class acts as a fully encapsulated entity--it is used as a whole unit. The actual inner workingsof the class should be hidden. Users of a well-defined class do not need to know how the class works;they just need to know how to use it. Inheritance and Reuse When the engineers at Acme Motors wantto build a new car, they have two choices: They can start from scratch, or they can modify an existingmodel. Perhaps their Star model is nearly perfect, but they'd like to add a turbocharger and a six-speed

transmission. The chief engineer would prefer not to start from the ground up, but rather to say, "Let'sbuild another Star, but let's add these additional capabilities. We'll call the new model a Quasar." AQuasar is a kind of Star, but one with new features.C supports the idea of reuse through inheritance. A new type, which is an extension of an existingtype, can be declared. This new subclass is said to derive from the existing type and is sometimescalled a derived type. The Quasar is derived from the Star and thus inherits all its qualities, but canadd to them as needed. Inheritance and its application in C are discussed on Day 12, "Inheritance,"and Day 15, "Advanced Inheritance." Polymorphism The new Quasar might respond differently than aStar does when you press down on the accelerator. The Quasar might engage fuel injection and aturbocharger, while the Star would simply let gasoline into its carburetor. A user, however, does nothave to know about these differences. He can just "floor it," and the right thing will happen,depending on which car he's driving.C supports the idea that different objects do "the right thing" through what is called functionpolymorphism and class polymorphism. Poly means many, and morph means form. Polymorphismrefers to the same name taking many forms, and is discussed on Day 10, "Advanced Functions," andDay 13, "Polymorphism."How C EvolvedAs object-oriented analysis, design, and programming began to catch on, Bjarne Stroustrup took themost popular language for commercial software development, C, and extended it to provide thefeatures needed to facilitate object-oriented programming. He created C , and in less than a decadeit has gone from being used by only a handful of developers at AT&T to being the programminglanguage of choice for an estimated one million developers worldwide. It is expected that by the endof the decade, C will be the predominant language for commercial software development.While it is true that C is a superset of C, and that virtually any legal C program is a legal C program, the leap from C to C is very significant. C benefited from its relationship to C formany years, as C programmers could ease into their use of C . To really get the full benefit of C ,however, many programmers found they had to unlearn much of what they knew and learn a wholenew way of conceptualizing and solving programming problems.The ANSI StandardThe Accredited Standards Committee, operating under the procedures of the American NationalStandards Institute (ANSI), is working to create an international standard for C .The draft of this standard has been published, and a link is available atwww.libertyassociates.com.The ANSI standard is an attempt to ensure that C is portable--that code you write f

Teach Yourself C in 21 Days, Second Edition Dedication This book is dedicated to the living memory of David Levine. Acknowledgments A second edition is a second chance to acknowledge and to thank those folks without whose support and help this book literally would have been impossible

Related Documents:

9781444106022 Complete Estonian: Teach Yourself 34.99 9781444105698 Complete Filipino (Tagalog) Audio Support: Teach Yourself 29.99 9781444105681 Complete Filipino (Tagalog) Book and CD Pack: Teach Yourself 59.99 9781444105674 Complete Filipino (Tagalog): Teach Yourself 29.99 9781444195248 Complete Finnish Audio Support: Teach Yourself (New Edition) 24.99 9781444195224 Complete .

Learning to forgive yourself is vitally important too. Hurting yourself, by refusing to forgive yourself, hurts others also. If you do not forgive yourself, then you will punish yourself by denying yourself the good things in life. The more you deny yourself the less you have to give. The less you

Tytuł oryginału: Sams Teach Yourself SQL in 10 Minutes, Fourth Edition Tłumaczenie: Rafał Jońca ISBN: 978-83-283-1089-6 Authorized translation from the English language edition: SAMS TEACH YOURSELF SQL IN 10

2 Getting onto the System and Using the Command Line 21 3 Moving About the File System 43 4 Listing Files and Managing Disk Usage 63 5 Ownership and Permissions 87 6 Creating, Moving, Renaming, and Deleting Files and Directories 113 . Sams Publishing. Teach Yourself UNIX in 24 Hours Teach Yourself UNIX in 24 Ho

Excerpt from: Sams Teach Yourself Responsive Web Design with HTML5 and CSS3 in 24 Hours ISBN: 978-0672338380 By Jennifer Kyrnin This is a free sample chapter from the book Sams Teach Yourself Responsive Web Design with HTML5 and . or wherever books are sold. mobile. When

Tytuł oryginału: Sams Teach Yourself Bootstrap in 24 Hours Tłumaczenie: Andrzej Watrak ISBN: 978-83-283-2514-2 Authorized translation from the English language edition, entitled: BOOTSTRAP IN 24 HOURS, SAMS TEACH YOURSELF; ISBN 0672337045; by Jennifer Kyrnin; published

Meloni, Julie C. Sams teach yourself HTML and CSS 24 hours / Julie Meloni, Michael Morrison. -- 8th ed. p. cm. Rev. ed. of: Sams teach yourself HTML and CSS in 24 hours / Dick Oliver, 7th ed., 2006. ISBN 978--672-33097-1 (pbk.) 1. HTML (Document markup language) 2. XHTML (Document markup language) 3. Cascading style sheets. I. Morrison .

Here are the steps to take to forgive yourself: The Healing Unfinished Business with Myself Exercise 1. Write down everything you are ashamed of. 2. Write down everything you feel guilty about. 3. Write a letter to yourself saying that you forgive yourself for all of it. 4. Write another letter to yourself, but this time, you’ll be writing