Author:Greg Perry & Dean Miller
No description
Tags
Support Statistics
¥.00 ·
0times
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
C Programming Greg Perry and Dean Miller 800 East 96th Street Indianapolis, Indiana 46240 Third Edition 00_9780789751980_fm.indd i 7/17/13 12:29 PM
Page
3
C Programming Absolute Beginner’s Guide Third Edition Copyright © 2014 by Pearson Education, Inc. All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. ISBN-13: 978-0-7897-5198-0 ISBN-10: 0-7897-5198-4 Library of Congress Control Number: 2013943628 Printe d in the United States of America Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Que Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The authors and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the programs accompanying it. Bulk Sales Que Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419 corpsales@pearsontechgroup.com For sales outside the United States, please contact International Sales international@pearsoned.com Acquisitions Editor Mark Taber Managing Editor Sandra Schroeder Project Editor Mandie Frank Copy Editor Krista Hansing Editorial Services, Inc. Indexer Brad Herriman Proofreader Anne Goebel Technical Editor Greg Perry Publishing Coordinator Vanessa Evans Interior Designer Anne Jones Cover Designer Matt Coleman Compositor TnT Design, Inc. Third Printing: January 2015
Page
4
Contents at a Glance Introduction ........................................................................................................... 1 Part I: Jumping Right In 1 What Is C Programming, and Why Should I Care? ................................ 5 2 Writing Your First C Program ..................................................................13 3 What Does This Do? Clarifying Your Code with Comments ...............23 4 Your World Premiere—Putting Your Program’s Results Up on the Screen .....................................................................................31 5 Adding Variables to Your Programs.......................................................41 6 Adding Words to Your Programs ...........................................................49 7 Making Your Programs More Powerful with #include and #define ........................................................................57 8 Interacting with Users ..............................................................................65 Part II: Putting C to Work for You with Operators and Expressions 9 Crunching the Numbers—Letting C Handle Math for You .................73 10 Powering Up Your Variables with Assignments and Expressions .......83 11 The Fork in the Road—Testing Data to Pick a Path .............................91 12 Juggling Several Choices with Logical Operators .............................103 13 A Bigger Bag of Tricks—Some More Operators for Your Programs ........................................................................................115 Part III: Fleshing Out Your Programs 14 Code Repeat—Using Loops to Save Time and Effort .......................123 15 Looking for Another Way to Create Loops .........................................131 16 Breaking in and out of Looped Code ..................................................141 17 Making the case for the switch Statement .....................................149 18 Increasing Your Program’s Output (and Input) ...................................163 19 Getting More from Your Strings ...........................................................171 20 Advanced Math (for the Computer, Not You!) ...................................181 Part IV: Managing Data with Your C Programs 21 Dealing with Arrays ................................................................................193 22 Searching Arrays.....................................................................................201 23 Alphabetizing and Arranging Your Data .............................................209 24 Solving the Mystery of Pointers ............................................................221 25 Arrays and Pointers ................................................................................231 26 Maximizing Your Computer’s Memory ................................................243 27 Setting Up Your Data with Structures ..................................................257 00_9780789751980_fm.indd iii 7/17/13 12:29 PM
Page
5
iv Part V: Files and Functions 28 Saving Sequential Files to Your Computer .........................................267 29 Saving Random Files to Your Computer .............................................277 30 Organizing Your Programs with Functions ..........................................285 31 Passing Variables to Your Functions ....................................................293 32 Returning Data from Your Functions ...................................................305 Appendixes A The ASCII Table .....................................................................................313 B The Draw Poker Program ......................................................................319 Index ..................................................................................................................331 00_9780789751980_fm.indd iv 7/17/13 12:29 PM
Page
6
Table of Contents Introduction ......................................................................................................................1 Who’s This Book For? ................................................................................................ 2 What Makes This Book Different? ........................................................................... 2 This Book’s Design Elements ................................................................................... 3 How Can I Have Fun with C? ................................................................................... 4 What Do I Do Now? .................................................................................................. 4 Part I: Jumping Right In 1 What Is C Programming, and Why Should I Care? ............................................5 What Is a Program? ................................................................................................... 6 What You Need to Write C Programs ..................................................................... 7 The Programming Process ......................................................................................10 Using C .....................................................................................................................11 2 Writing Your First C Program ..............................................................................13 A Down-and-Dirty Chunk of Code ........................................................................14 The main() Function .............................................................................................16 Kinds of Data ...........................................................................................................17 Characters and C ................................................................................................18 Numbers in C ......................................................................................................19 Wrapping Things Up with Another Example Program ........................................21 3 What Does This Do? Clarifying Your Code with Comments ..........................23 Commenting on Your Code ...................................................................................24 Specifying Comments .............................................................................................25 Whitespace ...............................................................................................................27 A Second Style for Your Comments ......................................................................28 4 Your World Premiere—Putting Your Program’s Results Up on the Screen .................................................................................................31 How to Use printf() ...........................................................................................32 The Format of printf() .................................................................................32 Printing Strings .........................................................................................................33 00_9780789751980_fm.indd v 7/17/13 12:29 PM
Page
7
vi Escape Sequences ...................................................................................................34 Conversion Characters ............................................................................................36 Putting It All Together with a Code Example .......................................................38 5 Adding Variables to Your Programs ...................................................................41 Kinds of Variables ....................................................................................................42 Naming Variables ....................................................................................................43 Defining Variables ....................................................................................................44 Storing Data in Variables ........................................................................................45 6 Adding Words to Your Programs ........................................................................49 Understanding the String Terminator ....................................................................50 The Length of Strings ..............................................................................................51 Character Arrays: Lists of Characters ....................................................................52 Initializing Strings .....................................................................................................54 7 Making Your Programs More Powerful with #include and #define .......57 Including Files ..........................................................................................................58 Placing #include Directives .................................................................................60 Defining Constants ..................................................................................................60 Building a Header File and Program .....................................................................62 8 Interacting with Users ...........................................................................................65 Looking at scanf() ...............................................................................................66 Prompting for scanf()..........................................................................................66 Problems with scanf() .........................................................................................68 Part II: Putting C to Work for You with Operators and Expressions 9 Crunching the Numbers—Letting C Handle Math for You ............................73 Basic Arithmetic .......................................................................................................74 Order of Operators .................................................................................................77 Break the Rules with Parentheses ..........................................................................79 Assignments Everywhere ........................................................................................80 00_9780789751980_fm.indd vi 7/17/13 12:29 PM
Page
8
vii 10 Powering Up Your Variables with Assignments and Expressions .................83 Compound Assignment ..........................................................................................84 Watch That Order! ...................................................................................................88 Typecasting: Hollywood Could Take Lessons from C ..........................................88 11 The Fork in the Road—Testing Data to Pick a Path ........................................91 Testing Data .............................................................................................................92 Using if ...................................................................................................................93 Otherwise…: Using else .......................................................................................96 12 Juggling Several Choices with Logical Operators ........................................ 103 Getting Logical ......................................................................................................104 Avoiding the Negative ..........................................................................................109 The Order of Logical Operators ..........................................................................111 13 A Bigger Bag of Tricks—Some More Operators for Your Programs ......... 115 Goodbye if…else; Hello, Conditional ..............................................................116 The Small-Change Operators: ++ and -- ..........................................................119 Sizing Up the Situation .........................................................................................121 Part III: Fleshing Out Your Programs 14 Code Repeat—Using Loops to Save Time and Effort .................................. 123 while We Repeat .................................................................................................124 Using while ..........................................................................................................125 Using do…while ...................................................................................................127 15 Looking for Another Way to Create Loops ................................................... 131 for Repeat’s Sake! ................................................................................................132 Working with for ..................................................................................................134 16 Breaking in and out of Looped Code ............................................................. 141 Take a break .........................................................................................................142 Let’s continue Working ......................................................................................145 00_9780789751980_fm.indd vii 7/17/13 12:29 PM
Page
9
viii 17 Making the case for the switch Statement ................................................ 149 Making the switch ..............................................................................................151 break and switch...............................................................................................153 Efficiency Considerations ......................................................................................154 18 Increasing Your Program’s Output (and Input) .............................................. 163 putchar() and getchar() ..............................................................................164 The Newline Consideration ..................................................................................167 A Little Faster: getch() ......................................................................................169 19 Getting More from Your Strings ...................................................................... 171 Character-Testing Functions .................................................................................172 Is the Case Correct? ..............................................................................................172 Case-Changing Functions.....................................................................................176 String Functions .....................................................................................................176 20 Advanced Math (for the Computer, Not You!) .............................................. 181 Practicing Your Math .............................................................................................182 Doing More Conversions ......................................................................................183 Getting into Trig and Other Really Hard Stuff ....................................................184 Getting Random ....................................................................................................187 Part IV: Managing Data with Your C Programs 21 Dealing with Arrays ............................................................................................ 193 Reviewing Arrays ...................................................................................................194 Putting Values in Arrays ........................................................................................197 22 Searching Arrays ................................................................................................. 201 Filling Arrays ...........................................................................................................202 Finders, Keepers ....................................................................................................202 23 Alphabetizing and Arranging Your Data ........................................................ 209 Putting Your House in Order: Sorting .................................................................210 Faster Searches ......................................................................................................215 00_9780789751980_fm.indd viii 7/17/13 12:29 PM
Page
10
ix 24 Solving the Mystery of Pointers ....................................................................... 221 Memory Addresses ................................................................................................222 Defining Pointer Variables ....................................................................................222 Using the Dereferencing * ...................................................................................225 25 Arrays and Pointers ............................................................................................ 231 Array Names Are Pointers ....................................................................................232 Getting Down in the List ......................................................................................233 Characters and Pointers ........................................................................................234 Be Careful with Lengths ........................................................................................234 Arrays of Pointers ..................................................................................................236 26 Maximizing Your Computer’s Memory ............................................................ 243 Thinking of the Heap ............................................................................................244 But Why Do I Need the Heap? ...........................................................................245 How Do I Allocate the Heap? ..............................................................................246 If There’s Not Enough Heap Memory .................................................................249 Freeing Heap Memory ..........................................................................................250 Multiple Allocations ...............................................................................................250 27 Setting Up Your Data with Structures ............................................................ 257 Defining a Structure ..............................................................................................258 Putting Data in Structure Variables ......................................................................262 Part V: Files and Functions 28 Saving Sequential Files to Your Computer .................................................... 267 Disk Files.................................................................................................................268 Opening a File .......................................................................................................268 Using Sequential Files ...........................................................................................270 29 Saving Random Files to Your Computer......................................................... 277 Opening Random Files .........................................................................................278 Moving Around in a File .......................................................................................279 00_9780789751980_fm.indd ix 7/17/13 12:29 PM
Page
11
x 30 Organizing Your Programs with Functions ..................................................... 285 Form Follows C Functions ....................................................................................286 Local or Global?.....................................................................................................290 31 Passing Variables to Your Functions ................................................................ 293 Passing Arguments ................................................................................................294 Methods of Passing Arguments ...........................................................................294 Passing by Value ...............................................................................................295 Passing by Address ..........................................................................................297 32 Returning Data from Your Functions ............................................................... 305 Returning Values ....................................................................................................306 The return Data Type .........................................................................................309 One Last Step: Prototype .....................................................................................309 Wrapping Things Up .............................................................................................312 Appendixes A The ASCII Table ................................................................................................... 313 B The Draw Poker Program .................................................................................. 319 Index ............................................................................................................................. 331 00_9780789751980_fm.indd x 7/17/13 12:29 PM
Page
12
xi About the Authors Greg Perry is a speaker and writer in both the programming and applications sides of computing. He is known for bringing programming topics down to the beginner’s level. Perry has been a programmer and trainer for two decades. He received his first degree in computer science and then earned a Master’s degree in corporate finance. Besides writing, he consults and lectures across the country, including at the acclaimed Software Development programming conferences. Perry is the author of more than 75 other computer books. In his spare time, he gives lectures on traveling in Italy, his second favorite place to be. Dean Miller is a writer and editor with more than 20 years of experience in both the publishing and licensed consumer product businesses. Over the years, he has created or helped shape a number of bestselling books and series, including Teach Yourself in 21 Days, Teach Yourself in 24 Hours, and the Unleashed series, all from Sams Publishing. He has written books on C programming and professional wrestling, and is still looking for a way to combine the two into one strange amalgam. 00_9780789751980_fm.indd xi 7/17/13 12:29 PM
Page
13
xii Dedication To my wife and best friend, Fran Hatton, who’s always supported my dreams and was an incredible rock during the most challenging year of my professional career. Acknowledgments Greg: My thanks go to all my friends at Pearson. Most writers would refer to them as editors; to me, they are friends. I want all my readers to understand this: The people at Pearson care about you most of all. The things they do result from their concern for your knowledge and enjoyment. On a more personal note, my beautiful bride, Jayne; my mother, Bettye Perry; and my friends, who wonder how I find the time to write, all deserve credit for supporting my need to write. Dean: Thanks to Mark Taber for considering me for this project. I started my professional life in computer book publishing, and it is so gratifying to return after a 10-year hiatus. I’d like to thank Greg Perry for creating outstanding first and second editions upon which this version of the book is based. It was an honor working with him as his editor for the first two editions and a greater honor to coauthor this edition. I can only hope I did it justice. I appreciate the amazing work the editorial team of Mandie Frank, Krista Hansing, and the production team at Pearson put into this book. On a personal level, I have to thank my three children, John, Alice, and Maggie and my wife Fran for their unending patience and support. 00_9780789751980_fm.indd xii 7/17/13 12:29 PM
Page
14
xiii We Want to Hear from You! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. We welcome your comments. You can email or write to let us know what you did or didn’t like about this book—as well as what we can do to make our books better. Please note that we cannot help you with technical problems related to the topic of this book and may not be able to reply personally to every message we receive. When you write, please be sure to include this book’s title, edition number, and authors, as well as your name and contact information. We will carefully review your comments and share them with the authors and editors who worked on the book. Email: feedback@quepublishing.com Mail: Que Publishing 800 East 96th Street Indianapolis, IN 46240 USA Reader Services Visit our website and register this book at http://informit.com/register for convenient access to any updates, downloads, or errata that might be available for this book. 00_9780789751980_fm.indd xiii 7/17/13 12:29 PM
Page
15
This page intentionally left blank
Page
16
INTRODUCTION Are you tired of seeing your friends get C programming jobs while you’re left out in the cold? Would you like to learn C but just don’t have the energy? Is your old, worn-out computer in need of a hot programming language to spice up its circuits? This book is just what the doctor ordered! C Programming Absolute Beginner’s Guide breaks the commonality of computer books by talking to you at your level without talking down to you. This book is like your best friend sitting next to you teaching C. C Programming Absolute Beginner’s Guide attempts to express without impressing. It talks to you in plain language, not in “computerese.” The short chapters, line drawings, and occasionally humorous straight talk guide you through the maze of C programming faster, friendlier, and easier than any other book available today. I N T H I S I N T R O D U C T I O N • Who’s This Book For? • What Makes This Book Different? • This Book’s Design Elements • How Can I Have Fun with C? • What Do I Do Now? 01_9780789751980_intro.indd 1 7/17/13 12:29 PM
Page
17
2 C PROGRAMMING ABSOLUTE BEGINNER’S GUIDE Who’s This Book For? This is a beginner’s book. If you have never programmed, this book is for you. No knowledge of any programming concept is assumed. If you can’t even spell C, you can learn to program in C with this book. The phrase absolute beginner has different meanings at different times. Maybe you’ve tried to learn C but gave up. Many books and classes make C much more technical than it is. You might have programmed in other languages but are a beginner in C. If so, read on, O faithful one, because in 32 quick chapters, you’ll know C. What Makes This Book Different? This book doesn’t cloud issues with internal technical stuff that beginners in C don’t need. We’re of the firm belief that introductory principles have to be taught well and slowly. After you tackle the basics, the “harder” parts never seem hard. This book teaches you the real C that you need to get started. C can be an extremely cryptic and difficult language. Many people try to learn C more than once. The problem is simply this: Any subject, whether it be brain surgery, mail sorting, or C programming, is easy if it’s explained properly. Nobody can teach you anything because you have to teach yourself—but if the instructor, book, or video doing the teaching doesn’t make the subject simple and fun, you won’t want to learn the subject. We challenge you to find a more straightforward approach to C than is offered in the C Programming Absolute Beginner’s Guide. If you can, call one of us because we’d like to read it. (You thought maybe we’d offer you your money back?) Seriously, we’ve tried to provide you with a different kind of help from that which you find in most other places. The biggest advantage this book offers is that we really like to write C programs— and we like to teach C even more. We believe that you will learn to like C, too. 01_9780789751980_intro.indd 2 7/17/13 12:29 PM
Page
18
INTRODUCTION 3 This Book’s Design Elements Like many computer books, this book contains lots of helpful hints, tips, warnings, and so on. You will run across many notes and sidebars that bring these specific items to your attention. TIP Many of this book’s tricks and tips (and there are lots of them) are highlighted as a Tip. When a really neat feature or code trick coincides with the topic you’re reading about, a Tip pinpoints what you can do to take advantage of the added bonus. NOTE Throughout the C language, certain subjects provide a deeper level of understanding than others. A Note tells you about something you might not have thought about, such as a new use for the topic being discussed. WARNING A Warning points out potential problems you could face with the particular topic being discussed. It indicates a warning you should heed or provides a way to fix a problem that can occur. Each chapter ends by reviewing the key points you should remember from that chapter. One of the key features that ties everything together is the section titled “The Absolute Minimum.” This chapter summary states the chapter’s primary goal, lists a code example that highlights the concepts taught, and provides a code analysis that explains that code example. You’ll find these chapter summaries, which begin in Chapter 2, “Writing Your First C Program,” to be a welcome wrap-up of the chapter’s main points. This book uses the following typographic conventions: • Code lines, variables, and any text you see onscreen appears in monospace. • Placeholders on format lines appear in italic monospace. • Parts of program output that the user typed appear in bold monospace. • New terms appear in italic. • Optional parameters in syntax explanations are enclosed in flat brackets ([ ]). You do not type the brackets when you include these parameters. 01_9780789751980_intro.indd 3 7/17/13 12:29 PM
Page
19
4 C PROGRAMMING ABSOLUTE BEGINNER’S GUIDE How Can I Have Fun with C? Appendix B, “The Draw Poker Program,” contains a complete, working Draw Poker program. The program was kept as short as possible without sacrificing readable code and game-playing functionality. The game also had to be kept generic to work on all C compilers. Therefore, you won’t find fancy graphics, but when you learn C, you’ll easily be able to access your compiler’s specific graphics, sound, and data-entry routines to improve the program. The program uses as much of this book’s contents as possible. Almost every topic taught in this book appears in the Draw Poker game. Too many books offer nothing more than snippets of code. The Draw Poker game gives you the chance to see the “big picture.” As you progress through this book, you’ll understand more and more of the game. What Do I Do Now? Turn the page and learn the C language. 01_9780789751980_intro.indd 4 7/17/13 12:29 PM
Page
20
WHAT IS C PROGRAMMING, AND WHY SHOULD I CARE? Although some people consider C to be difficult to learn and use, you’ll soon see that they are wrong. C is touted as being a cryptic program- ming language, and it can be—but a well-written C program is just as easy to follow as a program written in any other programming language. The demand for programmers and developers today is high, and learn- ing C is an effective foundation to build the skills needed in a variety of fields, including app development, game programming, and so much more. If you’ve never written a program in your life, this chapter is an excellent beginning because it teaches you introductory programming concepts, explains what a program is, and provides a short history of the C lan- guage. Get ready to be excited! C is a programming language rich in its capabilities. I N T H I S C H A P T E R 1 • Understanding the basics of C programming • Finding and installing a C compiler • Learning the steps of the programming process 02_9780789751980_ch01.indd 5 7/17/13 12:29 PM
Comments 0
Loading comments...
Reply to Comment
Edit Comment