C Programming Absolute Beginner’s Guide 3rd Edition PDF
Document Details
Uploaded by Deleted User
2014
Greg Perry and Dean Miller
Tags
Summary
This textbook provides a comprehensive guide to C programming, perfect for absolute beginners. It covers a wide range of topics, including syntax and concepts, from the fundamentals to advanced aspects of the language and its applications. The book's clear explanations and code examples make it an ideal resource for learning this essential skill set.
Full Transcript
About This eBook ePUB is an open, industry-standard format for eBooks. However, support of ePUB and its many features varies across reading devices and applications. Use your device or app settings to customize the presentation to your liking. Settings that you can customize often include font,...
About This eBook ePUB is an open, industry-standard format for eBooks. However, support of ePUB and its many features varies across reading devices and applications. Use your device or app settings to customize the presentation to your liking. Settings that you can customize often include font, font size, single or double column, landscape or portrait mode, and figures that you can click or tap to enlarge. For additional information about the settings and features on your reading device or app, visit the device manufacturer’s Web site. Many titles include programming code or configuration examples. To optimize the presentation of these elements, view the eBook in single-column, landscape mode and adjust the font size to the smallest setting. In addition to presenting code and configurations in the reflowable text format, we have included images of the code that mimic the presentation found in the print book; therefore, where the reflowable format may compromise the presentation of the code listing, you will see a “Click here to view code image” link. Click the link to view the print-fidelity code image. To return to the previous page viewed, click the Back button on your device or app. C Programming Third Edition Greg Perry and Dean Miller 800 East 96th Street Indianapolis, Indiana 46240 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 Printed in the United States of America First Printing: August 2013 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. 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 [email protected] For sales outside the United States, please contact International Sales [email protected] Contents at a Glance Introduction Part I: Jumping Right In 1 What Is C Programming, and Why Should I Care? 2 Writing Your First C Program 3 What Does This Do? Clarifying Your Code with Comments 4 Your World Premiere—Putting Your Program’s Results Up on the Screen 5 Adding Variables to Your Programs 6 Adding Words to Your Programs 7 Making Your Programs More Powerful with #include and #define 8 Interacting with Users Part II: Putting C to Work for You with Operators and Expressions 9 Crunching the Numbers—Letting C Handle Math for You 10 Powering Up Your Variables with Assignments and Expressions 11 The Fork in the Road—Testing Data to Pick a Path 12 Juggling Several Choices with Logical Operators 13 A Bigger Bag of Tricks—Some More Operators for Your Programs Part III: Fleshing Out Your Programs 14 Code Repeat—Using Loops to Save Time and Effort 15 Looking for Another Way to Create Loops 16 Breaking in and out of Looped Code 17 Making the case for the switch Statement 18 Increasing Your Program’s Output (and Input) 19 Getting More from Your Strings 20 Advanced Math (for the Computer, Not You!) Part IV: Managing Data with Your C Programs 21 Dealing with Arrays 22 Searching Arrays 23 Alphabetizing and Arranging Your Data 24 Solving the Mystery of Pointers 25 Arrays and Pointers 26 Maximizing Your Computer’s Memory 27 Setting Up Your Data with Structures Part V: Files and Functions 28 Saving Sequential Files to Your Computer 29 Saving Random Files to Your Computer 30 Organizing Your Programs with Functions 31 Passing Variables to Your Functions 32 Returning Data from Your Functions Appendixes A The ASCII Table B The Draw Poker Program Index Table of Contents Introduction 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? Part I: Jumping Right In 1 What Is C Programming, and Why Should I Care? What Is a Program? What You Need to Write C Programs The Programming Process Using C 2 Writing Your First C Program A Down-and-Dirty Chunk of Code The main() Function Kinds of Data Characters and C Numbers in C Wrapping Things Up with Another Example Program 3 What Does This Do? Clarifying Your Code with Comments Commenting on Your Code Specifying Comments Whitespace A Second Style for Your Comments 4 Your World Premiere—Putting Your Program’s Results Up on the Screen How to Use printf() The Format of printf() Printing Strings Escape Sequences Conversion Characters Putting It All Together with a Code Example 5 Adding Variables to Your Programs Kinds of Variables Naming Variables Defining Variables Storing Data in Variables 6 Adding Words to Your Programs Understanding the String Terminator The Length of Strings Character Arrays: Lists of Characters Initializing Strings 7 Making Your Programs More Powerful with #include and #define Including Files Placing #include Directives Defining Constants Building a Header File and Program 8 Interacting with Users Looking at scanf() Prompting for scanf() Problems with scanf() Part II: Putting C to Work for You with Operators and Expressions 9 Crunching the Numbers—Letting C Handle Math for You Basic Arithmetic Order of Operators Break the Rules with Parentheses Assignments Everywhere 10 Powering Up Your Variables with Assignments and Expressions Compound Assignment Watch That Order! Typecasting: Hollywood Could Take Lessons from C 11 The Fork in the Road—Testing Data to Pick a Path Testing Data Using if Otherwise...: Using else 12 Juggling Several Choices with Logical Operators Getting Logical Avoiding the Negative The Order of Logical Operators 13 A Bigger Bag of Tricks—Some More Operators for Your Programs Goodbye if...else; Hello, Conditional The Small-Change Operators: ++ and -- Sizing Up the Situation Part III: Fleshing Out Your Programs 14 Code Repeat—Using Loops to Save Time and Effort while We Repeat Using while Using do...while 15 Looking for Another Way to Create Loops for Repeat’s Sake! Working with for 16 Breaking in and out of Looped Code Take a break Let’s continue Working 17 Making the case for the switch Statement Making the switch break and switch Efficiency Considerations 18 Increasing Your Program’s Output (and Input) putchar() and getchar() The Newline Consideration A Little Faster: getch() 19 Getting More from Your Strings Character-Testing Functions Is the Case Correct? Case-Changing Functions String Functions 20 Advanced Math (for the Computer, Not You!) Practicing Your Math Doing More Conversions Getting into Trig and Other Really Hard Stuff Getting Random Part IV: Managing Data with Your C Programs 21 Dealing with Arrays Reviewing Arrays Putting Values in Arrays 22 Searching Arrays Filling Arrays Finders, Keepers 23 Alphabetizing and Arranging Your Data Putting Your House in Order: Sorting Faster Searches 24 Solving the Mystery of Pointers Memory Addresses Defining Pointer Variables Using the Dereferencing * 25 Arrays and Pointers Array Names Are Pointers Getting Down in the List Characters and Pointers Be Careful with Lengths Arrays of Pointers 26 Maximizing Your Computer’s Memory Thinking of the Heap But Why Do I Need the Heap? How Do I Allocate the Heap? If There’s Not Enough Heap Memory Freeing Heap Memory Multiple Allocations 27 Setting Up Your Data with Structures Defining a Structure Putting Data in Structure Variables Part V: Files and Functions 28 Saving Sequential Files to Your Computer Disk Files Opening a File Using Sequential Files 29 Saving Random Files to Your Computer Opening Random Files Moving Around in a File 30 Organizing Your Programs with Functions Form Follows C Functions Local or Global? 31 Passing Variables to Your Functions Passing Arguments Methods of Passing Arguments Passing by Value Passing by Address 32 Returning Data from Your Functions Returning Values The return Data Type One Last Step: Prototype Wrapping Things Up Appendixes A The ASCII Table B The Draw Poker Program Index 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. 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. 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: [email protected] 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. Introduction In This Introduction 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? 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. 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. 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. 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. Part I: Jumping Right In 1. What Is C Programming, and Why Should I Care? In This Chapter Understanding the basics of C programming Finding and installing a C compiler Learning the steps of the programming process 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 programming 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 learning 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 language. Get ready to be excited! C is a programming language rich in its capabilities. What Is a Program? A computer isn’t smart. Believe it or not, on your worst days, you are still light-years ahead of your computer in intelligence. You can think, and you can tell a computer what to do. Here is where the computer shines: It will obey your instructions. Your computer will sit for days processing the data you supply, without getting bored or wanting overtime pay. The computer can’t decide what to do on its own. Computers can’t think for themselves, so programmers (people who tell computers what to do) must give computers extremely detailed instructions. Without instructions, a computer is useless; with incorrect instructions, a computer will not successfully execute your desired task. A computer can no more process your payroll without detailed instructions than an automobile can start by itself and drive around the block independently. The collection of detailed expressions that you supply when you want your computer to perform a specific task is known as a program. Note Word processors, apps, spreadsheets, and computer games are nothing more than computer programs. Facebook is a collection of programs. Without such programs, the computer would just sit there, not knowing what to do next. A word-processing program contains a list of detailed instructions, written in a computer language such as C, that tells your computer exactly how to be a word processor. When you program, you are telling the computer to follow the instructions in the program you have supplied. You can buy or download thousands of programs for your computer, tablet, or phone, but when a business needs a computer to perform a specific task, that business hires programmers and developers to create software that follows the specifications the business needs. You can make your computer or mobile device do many things, but you might not be able to find a program that does exactly what you want. This book rescues you from that dilemma. After you learn C, you will be able to write programs that contain instructions that tell the computer how to behave. Tip A computer program tells your computer how to do what you want. Just as a chef needs a recipe to make a dish, a program needs instructions to produce results. A recipe is nothing more than a set of detailed instructions that, if properly written, describes that proper sequence and the contents of the steps needed to prepare a certain dish. That’s exactly what a computer program is to your computer. Programs produce output when you run or execute them. The prepared dish is a recipe’s output, and the word processor or app is the output produced by a running program. Warning Just as when a chef gets an ingredient wrong or misses a step in a recipe, the resulting dish can be inedible; if you mistype code or skip a step, your program will not work. What You Need to Write C Programs Before you can write and execute a C program on your computer, you need a C compiler. The C compiler takes the C program you write and builds or compiles it (technical terms for making the program computer-readable), enabling you to run the compiled program when you’re ready to look at the results. Luckily, many excellent free software packages are available in which you can edit and compile your C programs. A simple web search will provide a list. This book uses Code::Blocks (www.codeblocks.org). Tip If you run a search for “C Programming Compilers,” you’ll see a number of freeware options, including offerings from Borland and Microsoft. So why does this book use Code::Blocks? Because it offers versions for Windows, Macs, and Linux, so you can use a version of the software no matter what operating system you use. However, feel free to pick whichever programming environment looks best to you. If you surf to the Code::Blocks page and read the very first sentence, you may worry a bit (or a lot): The open source, cross platform, free C++ IDE. Open source refers to software code that users can alter or improve. (You will not be doing this anytime soon, so put it out of your mind.) Cross-platform is an adjective that means the software can run on different operating systems—as a beginner, however, you need concern yourself with only your own platform. I think free is a term we can all get behind, and IDE is short for integrated development environment, which just means you can write, edit, and debug your programs without having to switch software to do so. We get to debugging shortly. Don’t panic about the C++ part. You can write either C or C++ programs in Code::Blocks. Finding a C compiler these days is harder. Most of the time, C compilers come bundled with an advanced version of C, known as C++. Therefore, when you look for a C compiler, you will almost always find a combination C and C++ compiler, and often the C++ functionality is highlighted. The good news is that, after you learn C, you will already have a C++ compiler and you won’t have to learn the ins and outs of a new IDE. Figure 1.1 shows the Code::Blocks home page. To download the C/C++ IDE, click the Downloads choice under the Main section in the left column. FIGURE 1.1 The home page for Code::Blocks. You want to focus on the Downloads option. After you select Downloads, you are taken to a page that further discusses three options: Binaries, Source, and SVN. The latter two options are advanced, so you can ignore them. Click Binaries. Note Two things to consider when doing this installation. First, the screen shots in the book will probably be a little different than what you see on the Internet—Code::Blocks is constantly improving the software, so the numbers (which refer to the software version) are constantly increasing. The version of Code::Blocks used in the book was 10.05, but at last check, they are up to 12.11, and the number is probably even larger by the time you read this. Second, if you are a Windows user, make sure you select the larger file to download (which has mingw in its title). That version has debugging tools that will come in handy when you become a C-soned programmer. (Get it? No? Just me then?) The next page presents a variety of options, depending on your operating system. If you select the Windows option, choose the second option, highlighted in Figure 1.2. Having the full compiler and debugger will come in handy. FIGURE 1.2 Selecting the Windows IDE for download. You can choose either downloading source. After you choose to download the program, go get yourself a snack—it’s a big file, so it takes several minutes to completely download. When it does, click the file and accept all defaults. (Only seasoned programmers need to tweak the installation.) Soon enough, Code::Blocks will be running on your computer. After you exit the Tip of the Day and set Code::Blocks as the associated program with all.c and.cpp files, you can also close the scripting window. You should be left with the opening screen of the software, pictured in Figure 1.3. FIGURE 1.3 Welcome to your programming home! Note The C program you write is called source code. A compiler translates C source code into machine language. Computers are made up of nothing more than thousands of electrical switches that are either on or off. Therefore, computers must ultimately be given instructions in binary. The prefix bi- means “two,” and the two states of electricity are called binary states. It’s much easier to use a C compiler to convert your C programs into 1s and 0s that represent internal on and off switch settings than for you to do it yourself. The Programming Process Most people follow these basic steps when writing a program: 1. Decide exactly what the program should do. 2. Use an editor to write and save your programming language instructions. An editor is a lot like a word processor (although not usually as fancy) that lets you create and edit text. All the popular C compilers include an integrated editor along with the programming language compiler. All C program filenames end in the.c file extension. 3. Compile the program. 4. Check for program errors. If any appear, fix them and go back to step 3. 5. Execute the program. Note An error in a computer program is called a bug. Getting rid of errors is called debugging a program. Take some time to explore Code::Blocks or whatever compiler you choose to install on your computer. A robust IDE lets you perform these five steps easily, all from within the same environment. You can compile your program, view any errors, fix the errors, run the program, and look at the results, all from within the same screen and using a uniform set of menus. Warning If you have never programmed, this all might seem confusing. Relax. Most of today’s C compilers come with a handy tutorial you can use to learn the basics of the compiler’s editor and compiling commands. Just in case you still don’t fully understand the need for a compiler, your source code is like the raw materials that your computer needs. The compiler is like a machine that converts those raw materials to a final product, a compiled program that the computer can understand. Using C C is more efficient than most programming languages. It is also a relatively small programming language. In other words, you don’t have to learn many commands in C. Throughout this book, you will learn about C commands and other elements of the C language, such as operators, functions, and preprocessor directives. Because of the many possible versions of C, a committee known as the American National Standards Institute (ANSI) committee developed a set of rules (known as ANSI C) for all versions of C. As long as you run programs using an ANSI C compiler, you can be sure that you can compile your C programs on almost any computer that has an ANSI C compiler. Tip In 1983, ANSI created the X3J11 committee to set a standard version of C. This became known as ANSI C. The most recent version of ANSI C, C11, was formally adopted in 2011. As soon as you compile a C program, you can run the compiled program on any computer that is compatible with yours, whether or not the computer has an ANSI C compiler. “Great!” you might be saying. “But when do I get to write my first C program, let alone compile or run it?” Fear not —Chapter 2, “Writing Your First C Program,” takes you on your maiden C programming voyage. The Absolute Minimum This chapter introduced you to the C programming language and helped you select a compiler to edit, debug, and run your program. Here are a few key points to remember: Get a C compiler and install it on your computer. Get ready to learn the C programming language. Don’t worry that C is too complex. This book breaks down C concepts into easily digestible bits. With practice, you will do just fine. 2. Writing Your First C Program In This Chapter Typing your first program Using the main() function Identifying kinds of data You get to see your first C program in this chapter! Please don’t try to understand every character of the C programs discussed here. Relax and just get familiar with the look and feel of C. After a while, you will begin to recognize elements common to all C programs. A Down-and-Dirty Chunk of Code This section shows you a short but complete C program and discusses another program that appears in Appendix B, “The Draw Poker Program.” Both programs contain common and different elements. The first program is extremely simple: Click here to view code image #include main() { printf("Just one small step for coders. One giant leap for"); printf(" programmers!\n"); return 0; } Open your programming software and type in the program as listed. Simple, right? Probably not the first time you use your new compiler. When you open Code::Blocks for the first time, you will be greeted by a “Tip of the Day.” These tips will come in handy later, but right now you can just get rid of it by clicking Close. To create your program, Click the File Menu and select New. Choose Empty File from the options that appear on the submenu. Now you’ve got a nice clean file to start writing your seven-line program. After you type in your program, you will need to compile or build your program. To do this, click the little yellow gear icon in the upper-left corner. If you’ve typed the program in exactly and had no errors, you can then run the program by clicking the green right-facing arrow next to the gear. (The next icon in that row, with a gear and arrow, will do both the compiling and running of the program, simplifying your life by reducing the number of arduous clicks you must perform from two to one.) When you compile (or build) the program and run it, you should see something like Figure 2.1. FIGURE 2.1 The output of your first program. Note Producing that one-line message took a lot of work! Actually, of the eight lines in the program, only two—the ones that start with printf—do the work that produces the output. The other lines provide “housekeeping chores” common to most C programs. To see a much longer program, glance at Appendix B. Although the Draw Poker game there spans several pages, it contains elements common to the shorter program you just saw. Look through both the programs just discussed and notice any similarities. One of the first things you might notice is the use of braces ({}), parentheses (()), and backslashes (\). Be careful when typing C programs into your C compiler. C gets picky, for instance, if you accidentally type a square bracket ([) when you should type a brace. Warning In addition to making sure you don’t type the wrong character, be careful when typing code in a word processor and then copying it to your IDE. I typed the previous program in Word (for this book) and then copied it to Code::Blocks. When compiling the program, I received a number of errors because my quotes on the printf line were smart quotes created by the word processor (to give that cool slanted look), and the compiler did not recognize them. After I deleted the quotes on the line and retyped them in my programming editor, the code compiled just fine. So if you get errors in programs, make sure the quotes are not the culprit. C isn’t picky about everything. For instance, most of the spacing you see in C programs makes the programs clearer to people, not to C. As you program, add blank lines and indent sections of code that go together to help the appearance of the program and to make it easier for you to find what you are looking for. Tip Use the Tab key to indent instead of typing a bunch of spaces. Most C editors let you adjust the tab spacing (the number of spaces that appear when you press Tab). Some C program lines get long, so a tab setting of three provides ample indention without making lines too long. C requires that you use lowercase letters for all commands and predefined functions. (You learn what a function is in the next section.) About the only time you use uppercase letters is on a line with #define and inside the printed messages you write. The main() Function The most important part of a C program is its main() function. Both of the programs discussed earlier have main() functions. Although at this point the distinction is not critical, main() is a C function, not a C command. A function is nothing more than a routine that performs some task. Some functions come with C, and some are created by you. C programs are made up of one or more functions. Each program must always include a main() function. A function is distinguished from a command by the parentheses that follow the function name. These are functions: Click here to view code image main() calcIt() printf() strlen() and these are commands: Click here to view code image return while int if float When you read other C programming books, manuals, and webpages, the author might decide to omit the parenthesis from the end of function names. For example, you might read about the printf function instead of printf(). You’ll learn to recognize function names soon enough, so such differences won’t matter much to you. Most of the time, authors want to clarify the differences between functions and nonfunctions as much as possible, so you’ll usually see the parentheses. Warning One of the functions just listed, calcIt(), contains an uppercase letter. However, the preceding section said you should stay away from uppercase letters. If a name has multiple parts, as in doReportPrint(), it’s common practice to use uppercase letters to begin the separate words, to increase readability. (Spaces aren’t allowed in function names.) Stay away from typing words in all uppercase, but an uppercase letter for clarity once in a while is okay. The required main() function and all of C’s supplied function names must contain lowercase letters. You can use uppercase for the functions that you write, but most C programmers stay with the lowercase function name convention. Just as the home page is the beginning place to surf a website, main() is always the first place the computer begins when running your program. Even if main() is not the first function listed in your program, main() still determines the beginning of the program’s execution. Therefore, for readability, make main() the first function in every program you write. The programs in the next several chapters have only one function: main(). As you improve your C skills, you’ll learn why adding functions after main() improves your programming power even more. Chapter 30, “Organizing Your Programs with Functions,” covers writing your own functions. After the word main(), you always see an opening brace ({). When you find a matching closing brace (}), main() is finished. You might see additional pairs of braces within a main() function as well. For practice, look again at the long program in Appendix B. main() is the first function with code, and several other functions follow, each with braces and code. Note The statement #include is needed in almost every C program. It helps with printing and getting data. For now, always put this statement somewhere before main(). You will understand why the #include is important in Chapter 7, “Making Your Programs More Powerful with #include and #define.” Kinds of Data Your C programs must use data made up of numbers, characters, and words; programs process that data into meaningful information. Although many different kinds of data exist, the following three data types are by far the most common used in C programming: Characters Integers Floating points (also called real numbers) Tip You might be yelling “How much math am I going to have to learn?! I didn’t think that was part of the bargain!” Well, you can relax, because C does your math for you; you don’t have to be able to add 2 and 2 to write C programs. You do, however, have to understand data types so that you will know how to choose the correct type when your program needs it. Characters and C A C character is any single character that your computer can represent. Your computer knows 256 different characters. Each of them is found in something called the ASCII table, located in Appendix A, “The ASCII Table.” (ASCII is pronounced askee. If you don’t know-ee, you can just ask-ee.) Anything your computer can represent can be a character. Any or all of the following can be considered characters: A a 4 % Q ! + = ] Note The American National Standards Institute (ANSI), which developed ANSI C, also developed the code for the ASCII chart. Tip Even the spacebar produces a character. Just as C needs to keep track of the letters of the alphabet, the digits, and all the other characters, it has to keep track of any blank spaces your program needs. As you can see, every letter, number, and space is a character to C. Sure, a 4 looks like a number, and it sometimes is, but it is also a character. If you indicate that a particular 4 is a character, you can’t do math with it. If you indicate that another 4 is to be a number, you can do math with that 4. The same holds for the special symbols. The plus sign (+) is a character, but the plus sign also performs addition. (There I go, bringing math back into the conversation!) All of C’s character data is enclosed in apostrophes ('). Some people call apostrophes single quotation marks. Apostrophes differentiate character data from other kinds of data, such as numbers and math symbols. For example, in a C program, all of the following are character data: 'A' 'a' '4' '%' '' '-' None of the following can be character data because they have no apostrophes around them: A a 4 % - Tip None of the following are valid characters. Only single characters, not multiple characters, can go inside apostrophes. ‘C is fun’ ‘C is hard’ ‘I should be sailing!’ The first program in this chapter contains the character '\n'. At first, you might not think that \n is a single character, but it’s one of the few two-character combinations that C interprets as a single character. This will make more sense later. If you need to specify more than one character (except for the special characters that you’ll learn, like the \n just described), enclose the characters in quotation marks ("). A group of multiple characters is called a string. The following is a C string: “C is fun to learn.” Note That’s really all you need to know about characters and strings for now. In Chapters 4 through 6, you’ll learn how to use them in programs. When you see how to store characters in variables, you’ll see why the apostrophe and quotation marks are important. Numbers in C Although you might not have thought about it before now, numbers take on many different sizes and shapes. Your C program must have a way to store numbers, no matter what the numbers look like. You must store numbers in numeric variables. Before you look at variables, a review of the kinds of numbers will help. Whole numbers are called integers. Integers have no decimal points. (Remember this rule: Like most reality shows, integers have no point whatsoever.) Any number without a decimal point is an integer. All of the following are integers: 10 54 0 –121 –68 752 Warning Never begin an integer with a leading 0 (unless the number is zero), or C will think you typed the number in hexadecimal or octal. Hexadecimal and octal, sometimes called base-16 and base-8, respectively, are weird ways of representing numbers. 053 is an octal number, and 0x45 is a hexadecimal number. If you don’t know what all that means, just remember for now that C puts a hex on you if you mess around with leading zeroes before integers. Numbers with decimal points are called floating-point numbers. All of the following are floating- point numbers: 547.43 0.0 0.44384 9.1923 –168.470.22 Tip As you can see, leading zeroes are okay in front of floating-point numbers. The choice of using integers or floating-point numbers depends on the data your programs are working with. Some values (such as ages and quantities) need only integers; other values (such as money amounts or weights) need the exact amounts floating-point numbers can provide. Internally, C stores integers differently than floating-point values. As you can see from Figure 2.2, a floating-point value usually takes twice as much memory as an integer. Therefore, if you can get away with using integers, do so—save floating points for values that need the decimal point. FIGURE 2.2 Storing floating-point values often takes more memory than integers. Note Figure 2.2 shows you that integers generally take less memory than floating-point values, no matter how large or small the values stored there are. On any given day, a large post office box might get much less mail than a smaller one. The contents of the box don’t affect what the box is capable of holding. The size of C’s number storage is affected not by the value of the number, but by the type of the number. Different C compilers use different amounts of storage for integers and floating-point values. As you will learn later, there are ways of finding out exactly how much memory your C compiler uses for each type of data. Wrapping Things Up with Another Example Program This chapter’s goal was to familiarize you with the “look and feel” of a C program, primarily the main() function that includes executable C statements. As you saw, C is a free-form language that isn’t picky about spacing. C is, however, picky about lowercase letters. C requires lowercase spellings of all its commands and functions, such as printf(). At this point, don’t worry about the specifics of the code you see in this chapter. The rest of the book explains all the details. But it is still a great idea to type and study as many programs as possible— practice will increase your coding confidence! So here is a second program, one that uses the data types you just covered: Click here to view code image #include main() { printf("I am learning the %c programming language\n", 'C'); printf("I have just completed Chapter %d\n", 2); printf("I am %.1f percent ready to move on ", 99.9); printf("to the next chapter!\n"); return 0; } This short program does nothing more than print three messages onscreen. Each message includes one of the three data types mentioned in this chapter: a character (C), an integer (2), and a floating-point number (99.9). Note On the first printf statement, the %c tells the program where to introduce the character 'C'. It is %c as an abbreviation for character, not because the character is a C. If you were learning the N programming language, you would still use %c to place the 'N' character. The main() function is the only function in the program written by the programmer. The left and right braces ({ and }) always enclose the main() code, as well as any other function’s code that you might add to your programs. You’ll see another function, printf(), that is a built-in C function that produces output. Here is the program’s output: Click here to view code image I am learning the C programming language I have just completed Chapter 2 I am 99.9 percent ready to move on to the next chapter! Tip Try playing around with the program, changing the messages or data. You should even try making a mistake when typing, like forgetting a semicolon (;) at the end of a line, just to see what happens when you try to compile the program. Learning from mistakes can make you a better programmer! The Absolute Minimum This chapter familiarized you with the “look and feel” of a C program, primarily the main() function. The key points from this chapter include: A C function must have parentheses following its name. A C program consists of one or more functions. The main() function is always required. C executes main() before any other function. Put lots of extra spacing in your C programs, to make them more readable. Don’t put leading zeroes before integers unless the integer is zero. If you use a character, enclose it in single quotes. Strings go inside quotation marks. Integers are whole numbers without decimal points. Floating-point numbers have decimal points. 3. What Does This Do? Clarifying Your Code with Comments In This Chapter Commenting on your code Specifying comments Using whitespace Applying a second style for your comments Your computer must be able to understand your programs. Because the computer is a dumb machine, you must be careful to spell C commands exactly right and type them in the order you want them executed. However, people also read your programs. You will change your programs often, and if you write programs for a company, the company’s needs will change over time. You must ensure that your programs are understandable to people as well as to computers. Therefore, you should document your programs by explaining what they do. Commenting on Your Code Throughout a C program, you should add comments. Comments are messages scattered throughout your programs that explain what’s going on. If you write a program to calculate payroll, the program’s comments explain the gross pay calculations, state tax calculations, federal tax calculations, social security calculations, deductions, and all the other calculations that are going on. Note If you write the program and only you will use it, you don’t really need comments, right? Well, not exactly. C is a cryptic programming language. Even if you write the program, you aren’t always able to follow it later—you might forget why you wrote a particular chunk of code, so a comment will help to decipher matters. Tip Add comments as you write your programs. Get in the habit now, because programmers rarely go back and add comments later. When they must make a change later, programmers often lament about their program’s lack of comments. Another advantage is gained when commenting as you write the program instead of waiting until after you finish. While writing programs, you often refer back to statements you wrote earlier in the process. Instead of reinterpreting C code you’ve already written, you can scan through your comments, finding sections of code that you need faster. If you didn’t comment, you would have to decipher your C code every time you looked through a piece of it. Program maintenance is the process of changing a program over time to fix hidden bugs and to adapt the program to a changing environment. If you write a payroll program for a company, that company could eventually change the way it does payroll (to go from biweekly to weekly, as an example), and you (or another programmer) will have to modify the payroll program to conform to the company’s new payroll procedures. Commenting speeds program maintenance. With comments, you or another programmer can quickly scan through a program listing to find the areas that need changing. Comments are not C commands. C ignores every comment in your program. Comments are for people, and the programming statements residing outside the comments are for the computer. Consider the following C statement: return ((s1 < s2) ? s1 : s2); You don’t know C yet, but even if you did, this statement takes some study to figure out. Isn’t this better? Click here to view code image return ((s1 < s2) ? s1 : s2); The next section explains the syntax of comments, but for now, you can see that the message between the is a comment. The closer a comment is to spoken language and the further a comment is from C code, the better the comment is. Don’t write a comment just for the sake of commenting. The following statement’s comment is useless: Click here to view code image printf("Payroll"); Warning You don’t know C yet, and you still don’t need the preceding line’s comment! Redundant comments are a waste of your time, and they don’t add anything to programs. Add comments to explain what is going on to people (including yourself) who might need to read your program. Specifying Comments C comments begin with. Comments can span several lines in a program, and they can go just about anywhere in a program. All of the following lines contain C comments: Click here to view code image for (i = 0; i < 25; i++) Note Notice that comments can go on lines by themselves or before or after programming statements. The choice of placement depends on the length of the comment and the amount of code the comment describes. The Draw Poker program in Appendix B, “The Draw Poker Program,” contains all kinds of comments. By reading through the comments in that program, you can get an idea of what the program does without ever looking at the C code itself. Don’t comment every line. Usually only every few lines need comments. Many programmers like to place a multiline comment before a section of code and then insert a few smaller comments on lines that need them. Here is a complete program with different kinds of comments: Click here to view code image #include main() { float gift1, gift2, gift3, gift4, gift5; float total; printf("How much do you want to spend on your mom? "); scanf(" %f", &gift1); printf("How much do you want to spend on your dad? "); scanf(" %f", &gift2); printf("How much do you want to spend on your sister? "); scanf(" %f", &gift3); printf("How much do you want to spend on your brother? "); scanf(" %f", &gift4); printf("How much do you want to spend on your favorite "); printf("C Programming author? "); scanf(" %f", &gift5); total = gift1+gift2+gift3+gift4+gift5; printf("\nThe total you will be spending on gifts is $%.2f", total); return 0; } Many companies require that their programmers embed their own names in comments at the top of programs they write. If changes need to be made to the program later, the original programmer can be found to help. It’s also a good idea to include the filename that you use to save the program on disk at the beginning of a program so that you can find a program on disk when you run across a printed listing. Note This book might comment too much in some places, especially in the beginning chapters. You are so unfamiliar with C that every little bit of explanation helps. Tip For testing purposes, you might find it useful to comment out a section of code by putting around it. By doing this, you cause C to ignore that section of code, and you can concentrate on the piece of code you’re working on. Do not, however, comment out a section of code that already contains comments because you cannot embed one comment within another. The first */ that C runs across triggers the end of the comment you started. When C finds the next */ without a beginning. For single-line comments, you can also use //. C ignores the rest of the line after that point. Use whitespace and line breaks to make your programs easy to read. 4. Your World Premiere—Putting Your Program’s Results Up on the Screen In This Chapter Using printf() Printing strings Coding escape sequences Using conversion characters Putting it all together with a code example If neither you nor anybody else could see your program’s output, there would be little use for your program. Ultimately, you have to be able to view the results of a program. C’s primary means of output is the printf() function. No actual command performs output, but the printf() function is a part of every C compiler and one of the most used features of the language. How to Use printf() In a nutshell, printf() produces output on your screen. As the sample code listings in Chapters 2, “Writing Your First C Program,” and 3, “What Does This Do? Clarifying Your Code with Comments,” demonstrated, printf() sends characters, numbers, and words to the screen. There is a lot to printf(), but you don’t have to be an expert in all the printf() options (very few C programmers are) to use it for all your programs’ screen output. The Format of printf() The printf() function takes many forms, but when you get used to its format, printf() is easy to use. Here is the general format of printf(): Click here to view code image printf(controlString [, data]); Throughout this book, when you are introduced to a new command or function, you will see its basic format. The format is the general look of the statement. If something in a format appears in brackets, such as , data in the printf function just shown, that part of the statement is optional. You almost never type the brackets themselves. If brackets are required in the command, that is made clear in the text following the format. printf() requires a controlString, but the data following the controlString is optional. Warning printf() doesn’t actually send output to your screen, but it does send it to your computer’s standard output device. Most operating systems, including Windows, route the standard output to your screen unless you know enough to route the output elsewhere. Most of the time, you can ignore this standard output device stuff because you’ll almost always want output to go to the screen. Other C functions you will learn about later route output to your printer and disk drives. Note You might be wondering why some of the words in the format appear in italics. It’s because they’re placeholders. A placeholder is a name, symbol, or formula that you supply. Placeholders are italicized in the format of functions and commands to let you know that you should substitute something at that place in the command. Here is an example of a printf(): Click here to view code image printf("My favorite number is %d", 7); // Prints My favorite number // is 7 Because every string in C must be enclosed in quotation marks (as mentioned in Chapter 2), the controlString must be in quotation marks. Anything following the controlString is optional and is determined by the values you want printed. Note Every C command and function needs a semicolon (;) after it to let C know that the line is finished. Braces and the first lines of functions don’t need semicolons because nothing is executing on those lines. All statements with printf() should end in a semicolon. You won’t see semicolons after main(), however, because you don’t explicitly tell C to execute main(). You do, however, tell C to execute printf() and many other functions. As you learn more about C, you’ll learn more about semicolon placement. Printing Strings String messages are the easiest type of data to print with printf(). You have to enclose only the string in quotation marks. The following printf() prints a message on the screen: Click here to view code image printf("You are on your way to C mastery"); The message You are on your way to C mastery appears onscreen when the computer executes this statement. Note The string You are on your way to C mastery is the controlString in this printf(). There is little control going on here—just output. The following two printf() statements might not produce the output you expect: printf("Write code"); printf("Learn C"); Here is what the two printf() statements produce: Write codeLearn C Tip C does not automatically move the cursor down to the next line when a printf() executes. You must insert an escape sequence in the controlString if you want C to go to the next line after a printf(). Escape Sequences C contains a lot of escape sequences, and you’ll use some of them in almost every program you write. Table 4.1 contains a list of some of the more popular escape sequences. TABLE 4.1 Escape Sequences Note The term escape sequence sounds harder than it really is. An escape sequence is stored as a single character in C and produces the effect described in Table 4.1. When C sends '\a' to the screen, for example, the computer’s bell sounds instead of the characters \ and a actually being printed. You will see a lot of escape sequences in printf() functions. Any time you want to “move down” to the next line when printing lines of text, you must type \n so that C produces a newline, which moves the blinking cursor down to the next line on the screen. The following printf() statements print their messages on separate lines because of the \n at the end of the first one: printf("Write code\n"); printf("Learn C"); Tip The \n could have been placed at the beginning of the second line, and the same output would have occurred. Because escape sequences are characters to C, you must enclose them in quotation marks so that C knows that the escape sequences are part of the string being printed. The following also produces two lines of output: printf("Write code\nLearn C"); Double quotation marks begin and end a string, single quotation marks begin and end a character, and a backslash signals the start of an escape sequence, so they have their own escape sequences if you need to print them. \a rings your computer’s bell, \b moves the cursor back a line, and \t causes the output to appear moved over a few spaces. There are other escape sequences, but for now, these are the ones you are most likely to use. The following program listing demonstrates the use of all the escape sequences listed in Table 4.1. As always, your best bet is to try this program and then tweak it to something you’d like to try: Click here to view code image // Absolute Beginner's Guide to C, 3rd Edition // Chapter 4 Example 1--Chapter4ex1.c #include main() { printf("Column A\tColumn B\tColumn C"); printf("\nMy Computer\'s Beep Sounds Like This: \a!\n"); printf("\"Letz\bs fix that typo and then show the backslash "); printf("character \\\" she said\n"); return 0; } After you enter, compile, and run this code, you get the following results: Click here to view code image Column A Column B Column C My Computer's Beep Sounds Like This: ! "Let's fix that typo and then show the backslash character \" she said Note You should understand a few things about the previous listing. First, you must always place #include at the beginning of all programs that use the printf() function—it is defined in stdio.h, so if you fail to remember that line of code, you will get a compiler error because your program will not understand how to execute printf(). Also, different C/C++ compilers might produce a different number of tabbed spaces for the \t escape sequence. Finally, it is important to note that using the \b escape sequence overwrites anything that was there. That’s why the 'z' does not appear in the output, but the 's' does. Conversion Characters When you print numbers and characters, you must tell C exactly how to print them. You indicate the format of numbers with conversion characters. Table 4.2 lists a few of C’s most-used conversion characters. TABLE 4.2 Conversion Characters When you want to print a value inside a string, insert the appropriate conversion characters in the controlString. Then to the right of the controlString, list the value you want to be printed. Figure 4.1 is an example of how a printf() can print three numbers—an integer, a floating-point value, and another integer. FIGURE 4.1 printf() conversion characters determine how and where numbers print. Strings and characters have their own conversion characters as well. Although you don’t need %s to print strings by themselves, you might need %s when printing strings combined with other data. The next printf() prints a different type of data value using each of the conversion characters: Click here to view code image printf("%s %d %f %c\n", "Sam", 14, -8.76, 'X'); This printf() produces this output: Sam 14 -8.760000 X Note The string Sam needs quotation marks, as do all strings, and the character X needs single quotation marks, as do all characters. Warning C is strangely specific when it comes to floating-point numbers. Even though the - 8.76 has only two decimal places, C insists on printing six decimal places. You can control how C prints floating-point values by placing a period (.) and a number between the % and the f of the floating-point conversion character. The number you place determines the number of decimal places your floating-point number prints to. The following printf() produces four different-looking numbers, even though the same floating-point number is given: Click here to view code image printf("%f %.3f %.2f %.1f", 4.5678, 4.5678, 4.5678, 4.5678); C rounds the floating-point numbers to the number of decimal places specified in the %.f conversion character and produces this output: 4.567800 4.568 4.57 4.6 Tip You probably don’t see the value of the conversion characters at this point and think that you can just include the information in the controlString. However, the conversion characters will mean a lot more when you learn about variables in the next chapter. The printf() controlString controls exactly how your output will appear. The only reason two spaces appear between the numbers is that the controlString has two spaces between each %f. Putting It All Together with a Code Example Consider the following program listing: Click here to view code image #include main() { printf("Quantity\tCost\tTotal\n"); printf("%d\t\t$%.2f\t$%.2f\n", 3, 9.99, 29.97); printf("Too many spaces \b\b\b\b can be fixed with the "); printf("\\%c Escape character\n", 'b'); printf("\n\a\n\a\n\a\n\aSkip a few lines, and beep "); printf("a few beeps.\n\n\n"); printf("%s %c.", "You are kicking butt learning", 'C'); printf("You just finished chapter %d.\nYou have finished ", 4); printf("%.1f%c of the book.\n", 12.500, '%'); printf("\n\nOne third equals %.2f or ", 0.333333); printf("%.3f or %.4f or ", 0.333333, 0.333333); printf("%.5f or %.6f\n\n\n", 0.333333, 0.3333333); return 0; } Enter this code and compile and run the program. You get the output in Figure 4.2. FIGURE 4.2 Output from the second listing of Chapter 4. Notice that, because of the length of the word Quantity, the second line needed two tabs to fit the cost of the item under the Cost heading. You might not need this—you will just need to test your code to better understand how many spaces the tab escape sequence moves your cursor. Sometimes skipping one line isn’t enough, but luckily, you can place multiple \n characters to jump down as many lines as you want. Finally, seeing that the % sign is a big part of conversion characters, you cannot put one in your controlString and expect it to print. So if you need to print a percent sign on the screen, use the %c conversion character and place it that way. The Absolute Minimum The programs you write must be able to communicate with the user sitting at the keyboard. The printf() function sends data to the screen. Key points from this chapter to remember include: Every printf() requires a control string that determines how your data will look when printed. Don’t expect C to know how to format your data automatically. You must use conversion characters. Use escape sequences to print newlines, tabs, quotes, and backslashes, and to beep the computer as well. Unless you want your floating-point numbers to print to six places after the decimal point, use the %f conversion character’s decimal control. 5. Adding Variables to Your Programs In This Chapter Identifying kinds of variables Naming variables Defining variables Storing data in variables No doubt you’ve heard that computers process data. Somehow you’ve got to have a way to store that data. In C, as in most programming languages, you store data in variables. A variable is nothing more than a box in your computer’s memory that holds a number or a character. Chapter 2, “Writing Your First C Program,” explained the different types of data: characters, strings, integers, and floating points. This chapter explains how to store those types of data inside your programs. Kinds of Variables C has several different kinds of variables because there are several different kinds of data. Not just any variable will hold just any piece of data. Only integer variables can hold integer data, only floating-point variables can hold floating-point data, and so on. Note Throughout this chapter, think of variables inside your computer as acting like post office boxes in a post office. Post office boxes vary in size and have unique numbers that label each one. Your C program’s variables vary in size, depending on the kind of data they hold, and each variable has a unique name that differentiates it from other variables. The data you learned about in Chapter 2 is called literal data (or sometimes constant data). Specific numbers and letters don’t change. The number 2 and the character 'x' are always 2 and 'x'. A lot of data you work with—such as age, salary, and weight—changes. If you were writing a payroll program, you would need a way to store changing pieces of data. Variables come to the rescue. Variables are little more than boxes in memory that hold values that can change over time. Many types of variables exist. Table 5.1 lists some of the more common types. Notice that many of the variables have data types (character, integer, and floating point) similar to that of literal data. After all, you must have a place to store integers, and you do so in an integer variable. TABLE 5.1 Some of the Most Common Types of C Variables Tip In some older C compilers, int could hold only values between 32767 and - 32768. If you wanted to use a larger integer, you needed to use the long int type. In most modern compilers, though, an int type can hold the same as a long int type. If you’d like to be sure with your compiler, you can use the sizeof operator, covered in Chapter 13, “A Bigger Bag of Tricks—Some More Operators for Your Programs.” Warning You might notice that there are no string variables, although there are character string literals. C is one of the few programming languages that has no string variables, but as you’ll see in Chapter 6, “Adding Words to Your Programs,” you do have a way to store strings in variables. The Name column in Table 5.1 lists the keywords needed when you create variables for programs. In other words, if you want an integer, you need to use the int keyword. Before completing your study of variables and jumping into using them, you need to know one more thing: how to name them. Naming Variables All variables have names, and because you are responsible for naming them, you must learn the naming rules. All variable names must be different; you can’t have two variables in the same program with the same name. A variable can have from 1 to 31 characters in its name. Some compilers do allow longer names, but it’s better to stick with this limit, both for portability of code and to keep typing errors to a minimum. (After all, the longer the name you use, the greater the chance for a typo!) Your program’s variables must begin with a letter of the alphabet, but after that letter, variable names can have other letters, numbers, or an underscore in any combination. All of the following are valid variable names: Click here to view code image myData pay94 age_limit amount QtlyIncome Tip C lets you begin a variable name with an underscore, but you shouldn’t do so. Some of C’s built-in variables begin with an underscore, so there’s a chance you’ll overlap one of those if you name your variables starting with underscores. Take the safe route and always start your variable names with letters—I cannot underscore this point enough! (See what I did there?) The following examples of variable names are not valid: Click here to view code image 94Pay my Age lastname,firstname You ought to be able to figure out why these variable names are not valid: The first one, 94Pay, begins with a number; the second variable name, my Age, contains a space; and the third variable name, lastname, firstname, contains a special character (,). Warning Don’t name a variable with the same name as a function or a command. If you give a variable the same name as a command, your program won’t run; if you give a variable the same name as a function, you can’t use that same function name later in your program without causing an error. Defining Variables Before you use a variable, you have to define it. Variable definition (sometimes called variable declaration) is nothing more than letting C know you’ll need some variable space so it can reserve some for you. To define a variable, you only need to state its type, followed by a variable name. Here are the first few lines of a program that defines some variables: Click here to view code image main() { // My variables for the program char answer; int quantity; float price; The sample code just presented has three variables: answer, quantity, and price. They can hold three different types of data: character data, integer data, and floating-point data. If the program didn’t define these variables, it wouldn’t be able to store data in the variables. You can define more than one variable of the same data type on the same line. For example, if you wanted to define two character variables instead of just one, you could do so like this: Click here to view code image main() { // My variables for the program char first_initial; char middle_initial; or like this: Click here to view code image main() { // My variables for the program char first_initial, middle_initial; Tip Most C variables are defined after an opening brace, such as the opening brace that follows a function name. These variables are called local variables. C also lets you create global variables by defining the variables before a function name, such as before main(). Local variables are almost always preferable to global variables. Chapter 30, “Organizing Your Programs with Functions,” addresses the differences between local and global variables, but for now, all programs stick with local variables. Storing Data in Variables The assignment operator puts values in variables. It’s a lot easier to use than it sounds. The assignment operator is simply the equals sign (=). The format of putting data in variables looks like this: variable = data; The variable is the name of the variable where you want to store data. You must have defined the variable previously, as the preceding section explained. The data can be a number, character, or mathematical expression that results in a number. Here are examples of three assignment statements that assign values to the variables defined in the preceding section: answer = 'B'; quantity = 14; price = 7.95; You also can store answers to expressions in variables: Click here to view code image price = 8.50 *.65; // Gets price after 35% discount You can even use other variables in the expression: Click here to view code image totalAmount = price * quantity; Tip The equals sign tells C this: Take whatever is on the right and stick it into the variable on the left. The equals sign kind of acts like a left-pointing arrow that says “That-a- way!” Oh, and never use commas in numbers, no matter how big the numbers are! Let’s use all this variable knowledge you’ve gained in a program. Open your editor, type the following program, compile it, and run it: Click here to view code image // Example program #1 from Chapter 5 of Absolute Beginner's Guide // to C, 3rd Edition // File Chapter5ex1.c #include main() { // Set up the variables, as well as define a few char firstInitial, middleInitial; int number_of_pencils; int number_of_notebooks; float pencils = 0.23; float notebooks = 2.89; float lunchbox = 4.99; //The information for the first child firstInitial = 'J'; middleInitial = 'R'; number_of_pencils = 7; number_of_notebooks = 4; printf("%c%c needs %d pencils, %d notebooks, and 1 lunchbox\n", firstInitial, middleInitial,number_of_pencils, number_of_notebooks); printf("The total cost is $%.2f\n\n", number_of_pencils*pencils + number_of_notebooks*notebooks + lunchbox); //The information for the second child firstInitial = 'A'; middleInitial = 'J'; number_of_pencils = 10; number_of_notebooks = 3; printf("%c%c needs %d pencils, %d notebooks, and 1 lunchbox\n", firstInitial, middleInitial,number_of_pencils, number_of_notebooks); printf("The total cost is $%.2f\n\n", number_of_pencils*pencils + number_of_notebooks*notebooks + lunchbox); //The information for the third child firstInitial = 'M'; middleInitial = 'T'; number_of_pencils = 9; number_of_notebooks = 2; printf("%c%c needs %d pencils, %d notebooks, and 1 lunchbox\n", firstInitial, middleInitial,number_of_pencils, number_of_notebooks); printf("The total cost is $%.2f\n", number_of_pencils*pencils + number_of_notebooks*notebooks + lunchbox); return 0; } This program gives examples of naming and defining different types of variables, as well as assigning values to each. It’s important to note that you can reuse a variable by just assigning a new value to the variable. You might be wondering, why keep using and reusing variables if you are just going to change the value within the code itself? Why not just skip the variables and use the values in their place? The value of variables will become more apparent after Chapter 8, “Interacting with Users,” and you can get information from the user for these variables. The Draw Poker program in Appendix B, “The Draw Poker Program,” must keep track of a lot of things, and many variables are used there. At the start of most of the program’s functions, you’ll see a place where variables are being defined. Tip You can define variables and give them initial values at the same time. The previous program assigns values to the float variables pencil, notebook, and lunchbox when they are declared. The Absolute Minimum This chapter covered the different types of variables in C. Because there are different kinds of data, C has different variable kinds to hold that data. Key points from this chapter include: Learn how to name variables because almost all of your programs will use variables. Always define variables before you use them Don’t mix data types and variable types—you will get the wrong results if you do. If needed, you can define more than one variable on the same line. Don’t use a comma in a number. Enter the figure 100,000 as 100000, not 100,000. When storing values in variables, use the equals sign (=), also called the assignment operator. 6. Adding Words to Your Programs In This Chapter Understanding the string terminator Determining the length of strings Using character arrays: listing characters Initializing strings Although C doesn’t have string variables, you do have a way to store string data. This chapter explains how. You already know that you must enclose string data in quotation marks. Even a single character enclosed in quotation marks is a string. You also know how to print strings with printf(). The only task left is to see how to use a special type of character variable to hold string data so that your program can input, process, and output that string data. Understanding the String Terminator C does the strangest thing to strings: It adds a zero to the end of every string. The zero at the end of strings has several names: Null zero Binary zero String terminator ASCII 0 \0 Warning About the only thing you don’t call the string-terminating zero is zero! C programmers use the special names for the string-terminating zero so that you’ll know that a regular numeric zero or a character '0' is not being used at the end of the string; only the special null zero appears at the end of a string. C marks the end of all strings with the string-terminating zero. You never have to do anything special when entering a string literal such as "My name is Julie." C automatically adds the null zero. You’ll never see the null zero, but it is there. In memory, C knows when it gets to the end of a string only when it finds the null zero. Note Appendix A, “The ASCII Table,” contains an ASCII table (first mentioned in Chapter 2, “Writing Your First C Program”). The very first entry is labeled null, and the ASCII number for null is 0. Look further down at ASCII 48, and you’ll see a 0. ASCII 48 is the character '0', whereas the first ASCII value is the null zero. C puts the null zero at the end of strings. Even the string "I am 20" ends in an ASCII 0 directly after the character 0 in 20. The string terminator is sometimes called \0 (backslash zero) because you can represent the null zero by enclosing \0 in single quotes. Therefore, '0' is the character zero, and '\0' is the string terminator. (Remember the escape sequences covered in Chapter 4, “Your World Premiere—Putting Your Program’s Results Up on the Screen,” that were also single characters represented by two characters—a backslash followed by a letter or another character. Now you have a backslash number to add to the collection.) Figure 6.1 shows how the string "Crazy" is stored in memory. As you can see, it takes 6 bytes (a byte is a single memory location) to store the string, even though the string has only five letters. The null zero that is part of the string "Crazy" takes one of those six memory locations. FIGURE 6.1 A string always ends with a null zero in memory. The Length of Strings The length of a string is always the number of characters up to, but not including, the null zero. Sometimes you will need to find the length of a string. The null zero is never counted when determining the length of a string. Even though the null zero must terminate the string (so that C knows where the string ends), the null zero is not part of the string length. Given the definition of the string length, the following strings all have lengths of nine characters: Wednesday August 10 I am here When counting the length of strings, remember that you must account for every space. So although the second string has eight letters and numbers, as well as a space in the middle, and the third string has seven letters, as well as two spaces in the middle, are all considered nine-character strings. If you chose to put three spaces between August and 10 in the middle example, it would become an 11- character string. Warning The second string’s length doesn’t end at the 0 in 10 because the 0 in 10 isn’t a null zero; it’s a character zero. Tip All single characters of data have a length of 1. Therefore, both 'X' and "X" have lengths of one, but the "X" consumes two characters of memory because of its null zero. Any time you see a string literal enclosed in quotation marks (as they all must be), picture in your mind that terminating null zero at the end of that string in memory. Character Arrays: Lists of Characters Character arrays hold strings in memory. An array is a special type of variable that you’ll hear much more about in upcoming chapters. All the data types—int, float, char, and the rest—have corresponding array types. An array is nothing more than a list of variables of the same data type. Before you use a character array to hold a string, you must tell C that you need a character array in the same place you would tell C that you need any other kind of variable. Use brackets ([ and ]) after the array name, along with a number indicating the maximum number of characters the string will hold. An example is worth a thousand words. If you needed a place to hold month names, you could define a character array called month like this: Click here to view code image char month; Tip Array definitions are easy. Take away the 10 and the brackets, and you have a regular character variable. Adding the brackets with the 10 tells C that you need 10 character variables, each following the other in a list named month. The reason 10 was used when defining the array is that the longest month name, September, has nine characters. The tenth character is for, you guessed it, the null zero. Tip You always have to reserve enough character array space to hold the longest string you will need to hold, plus the string terminator. You can define more array characters than needed, but not fewer than you need. If you want, you can store a string value in the array at the same time you define the array: Click here to view code image char month = "January"; Figure 6.2 shows you what this array looks like. Because nothing was put in the last two places of the array (January takes only seven characters plus an eighth place for the null zero), you don’t know what’s in the last two places. (Some compilers, however, fill the unused elements with zeroes to kind of empty the rest of the string.) FIGURE 6.2 Defining and initializing an array named month that holds string data. Each individual piece of an array is called an element. The month array has 10 elements. You can distinguish between them with subscripts. Subscripts are numbers that you specify inside brackets that refer to each of the array elements. All array subscripts begin with 0. As Figure 6.2 shows, the first element in the month array is called month. The last is called month because there are 10 elements altogether, and when you begin at 0, the last is 9. Each element in a character array is a character. The combination of characters—the array or list of characters—holds the entire string. If you wanted to, you could change the contents of the array from January to March one element at a time, like this: Click here to view code image Month = 'M'; Month = 'a'; Month = 'r'; Month = 'c'; Month = 'h'; Month = '\0'; //You must add this It is vital that you insert the null zero at the end of the string. If you don’t, the month array would still have a null zero three places later at Month; when you attempted to print the string, you would get this: Marchry Tip Printing strings in arrays is easy. You use the %s conversion character: Click here to view code image printf("The month is %s", month); If you define an array and initialize the array at the same time, you don’t have to put the number in brackets. Both of the following do exactly the same thing: char month = "January"; char month[] = "January"; In the second example, C counts the number of characters in January and adds one for the null zero. You can’t store a string larger than eight characters later, however. If you want to define a string’s character array and initialize it but leave extra padding for a longer string later, you would do this: Click here to view code image char month = "January"; Initializing Strings You don’t want to initialize a string one character at a time, as done in the preceding section. However, unlike with regular nonarray variables, you can’t assign a new string to the array like this: Click here to view code image month = "April"; You can assign a string to a month with the equals sign only at the time you define the string. If later in the program you want to put a new string into the array, you must either assign it one character at a time or use C’s strcpy() (string copy) function that comes with your C compiler. The following statement assigns a new string to the month: Click here to view code image strcpy(month, "April"); Note In your programs that use strcpy(), you must put this line after the #include : #include Tip Don’t worry: strcpy() automatically adds a null zero to the end of the string it creates. Now let’s take everything we’ve covered in this chapter and put it to use in a full program. Again, it’s time to fire up your editor, enter some code, and compile and run the resulting program: Click here to view code image // Example program #1 from Chapter 6 of // Absolute Beginner's Guide to C, 3rd Edition // File Chapter6ex1.c // This program pairs three kids with their favorite superhero #include #include main() { char Kid1; // Kid1 can hold an 11-character name // Kid2 will be 7 characters (Maddie plus null 0) char Kid2[] = "Maddie"; // Kid3 is also 7 characters, but specifically defined char Kid3 = "Andrew"; // Hero1 will be 7 characters (adding null 0!) char Hero1 = "Batman"; // Hero2 will have extra room just in case char Hero2 = "Spiderman"; char Hero3; Kid1 = 'K'; //Kid1 is being defined character-by-character Kid1 = 'a'; //Not efficient, but it does work Kid1 = 't'; Kid1 = 'i'; Kid1 = 'e'; Kid1 = '\0'; // Never forget the null 0 so C knows when the // string ends strcpy(Hero3, "The Incredible Hulk"); printf("%s\'s favorite hero is %s.\n", Kid1, Hero1); printf("%s\'s favorite hero is %s.\n", Kid2, Hero2); printf("%s\'s favorite hero is %s.\n", Kid3, Hero3); return 0; } As with the program that ended Chapter 5, “Adding Variables to Your Program,” you might be saying, why go through all the trouble of having these variables when you could just put the names and strings right in the printf() statements? Again, the value of these variables will become more apparent after Chapter 8, “Interacting with Users,” when you learn to get information from users. You were already using #include to add the file to all your programs that use printf() (as well as other common functions that you will soon be adding to your programming toolbox). Now you have a second header file, , to #include as well. The next chapter covers #include in more detail. To remind you of the different methods of declaring and initializing string variables, the kid and hero variables are each defined differently. For a fun exercise, comment out the strcpy line to see what your program prints on the screen when Hero3 is used in a printf() without having been initialized. My output was a bizarre collection of characters—those were already sitting in the space that became that variable, so if you don’t put anything in it, you’ll get whatever is there now. The Absolute Minimum If you need to store words, you need to use character arrays; C does not support a string data type. Key points from this chapter include: Store strings in character arrays, but reserve enough array elements to hold the longest string you’ll ever store in that array. Don’t forget that strings must end with a terminating zero. When writing to your array, remember that the subscripts begin at 0, not 1. There are three ways to place a string in a character array: You can initialize it at the time you define the array, you can assign one element at a time, or you can use the strcpy() function. If you use the strcpy() function in your programs, remember to add #include to the beginning of your program. 7. Making Your Programs More Powerful with #include and #define In This Chapter Including files Placing #include directives Defining constants Building a header file and program Two types of lines you see in many C programs are not C commands at all. They are preprocessor directives. A preprocessor directive always begins with a pound sign (#). Preprocessor directives don’t cause anything to happen at runtime (when you run your program). Instead, they work during the compiling of your program. These preprocessor directives are used most often: #include #define Every sample program you have written so far has used #include. This chapter finally takes the secret out of that mysterious preprocessor directive. Including Files #include has two formats, which are almost identical: #include and #include "filename" Figure 7.1 shows what #include does. It’s nothing more than a file merge command. Right before your program is compiled, the #include statement is replaced with the contents of the filename specified after #include. The filename can be stated in either uppercase or lowercase letters, as long as your operating system allows for either in filenames. For example, my Windows XP implementation of Code::Blocks does not distinguish between uppercase and lowercase letters in filenames, but UNIX does. If your file is named myFile.txt, you might be able to use any of the following #include directives: #include "MYFILE.TXT" #include "myfile.txt" #include "myFile.txt" However, UNIX allows only this: #include "myFile.txt" FIGURE 7.1 #include inserts a disk file into the middle of another file. Note When you’ve used a word processor, you might have used an #include type of command if you merged a file stored on disk into the middle of the file you were editing. When you install your compiler, the installation program sets up a separate location on your disk (in a directory) for various #include files that come with your compiler. When you want to use one of these built-in #include files, use the #include format with the angled brackets, < and >. Warning How do you know when to use a built-in #include file? Good question! All built-in functions, such as printf(), have corresponding #include files. When this book describes a built-in function, it also tells you exactly which file to include. You’ve already used two built-in functions in your programs: printf() and strcpy(). (main() is not a built-in C function; it is a function you must supply.) As a reminder, the #include file for printf() is stdio.h (which stands for standard I/O), and the #include file for the strcpy() function is string.h. Almost every complete program listing in this book contains the following preprocessor directive: #include That’s because almost every program in this book uses printf(). Chapter 6, “Adding Words to Your Program,” told you that whenever you use the strcpy() function, you need to include string.h. Tip The file you include is called a header file. That’s why most included files end in the extension.h. When you write your own header files, use the second form of the preprocessor directive, the one that has quotation marks. When you use quotation marks, C first searches the disk directory in which your program is stored and then searches the built-in #include directory. Because of the search order, you can write your own header files and give them the same name as those built into C, and yours will be used instead of C’s. Warning If you write your own header files, don’t put them with C’s built-in #include file directory. Leave C’s supplied header files intact. There is rarely a reason to override C’s headers, but you might want to add some headers of your own. You might write your own header files when you ha