C by Example. By Greg Perry . Labels: book pdf free download Lara Abbaschian Physical Metallurgy Principles Reza Abbaschian Robert E. would also like to give special thanks to our technical editor, Greg Perry, who is a true C expert complicated and often misunderstood world of C programming. Updated for C11 Write powerful C programs without becoming a technical expert! by Dean Miller, Greg Perry A Down-and-Dirty Chunk of Code · The main() Function · Kinds of Data · Wrapping Things Up with Another Example Program.
|Language:||English, Spanish, German|
|ePub File Size:||23.71 MB|
|PDF File Size:||12.74 MB|
|Distribution:||Free* [*Regsitration Required]|
C by Example-Que ()-Greg Perry - Ebook download as PDF File .pdf), Text File .txt) or read book online. C by Example-Que ()-Greg Perry. consultant and a lecturer. Greg Perry is the author of 11 other computer books, including QBASIC By Example and C By Example. In addition, he has published . Greg Perry and Dean Miller . Part II: Putting C to Work for You with Operators and Expressions. 9 a code analysis that explains that code example. You'll.
Previously, Greg taught advanced programming courses at Tulsa Community College. When you are taught to write clear and concise C code. To write a program you should 1. Instead of typing the same required portions of the program every time the programmer begins. The for Statement The for statement encloses one or more C statements that form the body of the loop.
It's the reason you always get the best out of them. Take only the most applicable parts of your favourite materials and combine them in any order you want. You can even integrate your own material if you wish. It's fast, it's easy and fewer course materials help minimise costs for your students. For more information: Explore our range of textbook content across the disciplines and see how you can create your own textbook or eBook.
Pick and choose content from one or more texts plus carefully-selected third-party content, and combine it into a bespoke book, unique to your course. You can also include skills content, your own material and brand it to your course and your institution.
Read about Durham University's experience of creating a bespoke course eBook for their engineering students catalogue. Pearson Learning Solutions will partner with you to create a completely bespoke technology solution to your course's specific requirements and needs. Develop websites just for your course, acting as a bespoke 'one-stop shop' for you and your students to access eBooks, MyLab or Mastering courses, videos and your own original material.
Include highly engaging bespoke games, animations and simulations to aid students' understanding, promote active learning and accommodate their differing learning styles. Customise existing Pearson eLearning content to match the specific needs of your course. Simply share your course goals with our world-class experts, and they will offer you a selection of outstanding, up-to-the-minute solutions. Looking for technical support for your Pearson course materials?
Please visit our Technical Support site. Browse by discipline. Sign in Find your rep Exam copy bookbag Basket. Mass Comm Communication: Civil and Environmental Engineering: Electrical Engineering: Industrial Engineering: Intro Level Engineering: Mechanical English: Continue browsing View my bookbag. Updating your exam copy bookbag…. View BookBag. You have selected an online exam copy, you will be re-directed to the VitalSource website where you can complete your request Get your digital copy.
No sampling allowed. C by Example. Overview Packages. Print this content. In this section: Features By example approach within each chapter — Numerous examples and sample programs demonstrate ways to use the concepts students have just learned. Help guide students through the chapters. Teaches students the key building blocks of C. Provides students with the concepts to make their C programs more effective.
Shows students practical applications for using C. This means that as soon as you fill your computer's memory with 32 million bytes. These fundamental principles are presented here for you to learn. Before describing the physical layout of your computer's memory. A byte is any character. If your computer contains 32 megabytes of memory. After reading this appendix. You should take the time to learn about addressing.
Structure member 2! B backup file—A copy of a file that preserves your work in case the original file is damaged. This defines a unique number for each character the computer can produce. Each bit has a value of 0 or 1. This can be a constant or a variable. Glossary A address—A sequential number. Also called a text file.
C's arguments are always enclosed in parentheses. See also binary. See also bit. C blocks are always enclosed within braces. A byte is equivalent to eight bits and can contain a value ranging from 0 through This term originated when a moth short-circuited a printer's connection.
See also preprocessor directives '' quotation marks. NOT operator. If you are new to C. C by Example is for you! Visual Basic for Applications.
Neither is any liability assumed for damages resulting from the use of the information contained herein. No patent liability is assumed with respect to the use of the information contained herein. International Standard Book Number: December 01 00 99 4 3 2 1 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized.
No part of this book shall be reproduced. Although every precaution has been taken in the preparation of this book. 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. The information provided is on an ''as is" basis. The author 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.
Que cannot attest to the accuracy of this information. Lowe Managing Editor Thomas F. Hayes Project Editor Karen S. Until that time.
C is no more difficult to learn or use than any other programming language. Bell Labs first developed this language in the early s. Companies looking for programmers in these newer. This does not have to be the case. C was the most popular programming language being used. C Is Fundamental Just a few years ago.
The reason for C's recommended mastery. TIP Due to the Internet's phenomenal growth. The companies know that someone well-versed in C can pick up these offshoot languages rapidly. In fact. Rarely will a project be written in C. C was standardized so that the same program would run on every kind of computer using every kind of operating system available. C is much simpler to learn than these languages because it carries with it a much slimmer toolkit of add-on procedures.
Programmers wrote C code for PCs. The History of C Before you jump into C. When you are taught to write clear and concise C code. C is considered to be the one language it is imperative a programmer master before moving on to the other languages in use today.
C is known also as a weakly typed language. How C Differs If you have programmed before. Although the. Although you can get into trouble a little more easily. Today's new C-based languages. C is an extremely flexible language—particularly if it is to be used to write operating systems. BCPL strongly influenced C. At any one time. NOTE C's philosophy is this: Trust the programmers—they must know what they're doing! The added responsibility of the weakly typed. The Bell Labs designers knew they needed a higher-level programming language to implement their project quicker and make its code easier to maintain.
C enables you to do this. Proper coding techniques learned in this book. C is efficient it is sometimes called a high low-level language due to its speed of execution and flexible. C enables you to view the same data in different ways.
These languages require rigid conformity to consistent data types. After a few versions. The data may not be in the format you expect. Besides being a very efficient language. If you declare a numeric variable. C's weakly typed nature places much more responsibility on the programmer.
After you use the editor to type the program. You also should eventually become familiar with binary and hexadecimal numbers.
An editor is similar to a word processor. Only after compiling the C program that you write can your computer run the program and show the results from that program.
To write and execute a C program. Unless the only language in your background is an interactive language such as QBasic. Many of today's compilers come with their own built-in editor. This book teaches C in a text-based environment so that you can concentrate on learning the language and all its nuances. If you do not want to learn these topics.
The compiler takes the C instructions you write and converts those instructions to code the computer can understand.
NOTE Actually. UNIX computers also run windowing environments. Write the program using the editor. Design the program's output what the user should see. While you are programming.
C filename extension as opposed to the. But the computer follows your instructions only after you run the program. When builders construct houses. Define the problem to be solved with the computer. Example The hardest part of writing a program is breaking the problem into logical steps that the computer can follow. They first find out what the owner of the house wants. Break the problem into logical steps to achieve this output. To write a program you should 1.
Proper Program Design You must plan your programs before typing them into your C editor. Your program contains only the C instructions that you write. Learning C is a requirement. There is a method of writing programs—a formal procedure you should learn—that makes your programming job easier. The results are the output of the program. All C programs use the. Throughout this book's examples. C filename extension. As you can see from this procedure.
Test the program to make sure it performs as you expect. Compile the program. Designing the program in advance makes the entire program structure more accurate. A builder. This is important. Planning and developing according to these six steps becomes much more important as you write longer and more complicated programs.
The process you use to compile your program depends on the version of C and the computer you are using. The compiler is just a way to transform your program from a source code file to an executable file. Your goal of good programming is the result of whatever applications you produce. C source code can contain preprocessor directives that control the way your programs compile.
Your program must go through one additional stage after compiling and before running. But now it's time to launch into C. Throughout this book. You can also combine several compiled programs into one. You do not have to follow the file-naming conventions used in this book. You may have to refer to your compiler's reference manuals or to your company's system personnel to learn how to compile programs for your programming environment.
The Compile Process After you type and edit your C program's source code. Unlike many other programming languages. NOTE Each program in this book contains a comment that specifies a recommended filename for the source program. It is always more difficult to make major changes after your program is written. It is called the linking.
When your program is linked. If you use a mainframe. Most of the time. This may or may not be a trivial task depending on your compiler. Compiling C source code into an executable program. Some Windows-based compilers are loaded with so many features that doing something simple. Figure 1. Running a Program One of the most important tasks you can perform now is to start your C compiler.
Entering a program should be relatively simple because an editor works like a simple word processor for programs that you enter. NOTE Be sure to install your compiler and familiarize yourself with your compiler's editor. C extension. Be as accurate as possible—a single typing mistake could cause the C compiler to. Starting with Chapter 2. Output The program from Listing 1. After it prints your name for the fifth time. After its programmers tried for many hours to find the problem in the program.
If you don't understand the error. The worst thing that may happen is your computer will freeze and you'll have to reboot and restart your C compiler. Here is a sample execution of the program: What is your first name? After you have typed your program correctly using the editor and you get no compile errors. The most common error is a syntax error. If you misspell a word.
When you get an error message or more than one. When she removed the moth.
Grace Hopper is now a retired admiral from the Navy and. She found a small moth lodged between two important wires. TIP As you progress through this book. You may not understand everything in this program. Although the program does not do a lot. The next few sections discuss elements from this and other programs. Studying a Program Figure 2. Begin analyzing C programs with this general outline. The structure of these other programs often mimics that of C programs. Figure 2. Listing 2.
A simple C program gives you general insight into the nature of the C language. Although there is much more to a C program than Figure 2. Example To get acquainted with C programs as quickly as possible.
The program is simple so you can start easy. The figure contains no commands or variables. Of course. See whether or not you can understand part of all of the program in Listing 2. Begin to familiarize yourself with the structure of C program code. Since you are not completely new to programming.
The Format of a C Program You can include as much white space separating lines and spaces in your C programs as you. Blank lines help separate the sections of the program from each other. The more readable your program is. Insert as many blank lines in your programs as you wish. NOTE C is called a free-form language—unlike some other languages. Example Your goal should not be to make your programs as compact as possible. The sample program shown in Listing 2. Your goal should be to make your programs as readable as possible.
C program shown in Listing 2. Even in today's world of fast computers and abundant memory and disk space. Even if nobody else ever looks at your C program. C you'll find the name of each program in this book in the first line of each program listing. By eliminating extra space. For example. C contains several blank lines to help separate parts of the program from each other.
Readability Is the Key As long as programs do their job and produce correct output. If you work as a programmer for a company. The more readable you make your program. Not one C command uses uppercase letters. To continue a quoted phrase on the next line to keep a single statement from becoming too lengthy. Use lots of white space so you can have separate lines and spaces throughout your programs.
TIP You can break a line just about anywhere except between a quoted phrase. This indention helps programmers "zero in" on the important code. If you use uppercase letters. When you write programs that contain several sections called blocks. C start in the first column. Many C programmers reserve uppercase characters for some words and messages sent to the screen. In programming departments. C is lowercase. Given this new global economy and all the changes that will face business in the years ahead.
The entire C language is in lowercase. Uppercase Versus Lowercase Your uppercase and lowercase letters are much more significant in C than in most other programming languages. There is. Everything between two matching braces is called a block. All executable C statements must have a semicolon. The function called main is always required and always the first function executed. Instead of typing the same required portions of the program every time the programmer begins.
A C program is actually a collection of functions small sections of code. Braces and mainx All C programs require the following lines: You read more about blocks later. As you become better acquainted with C.
For now. Many beginning C programmers learn quickly when semicolons are required. In the sample program. The section of a C program that begins with main. Because the computer ignores all comments. TIP Many programmers use program templates that are nothing more than skeleton programs with the typical main and other C program elements already in the code.
It contains additional markings to. Notice that the lines containing main and braces do not end with semicolons either.
Comments can span more than one line. C Comments As a programmer in another language before you began learning C. As explained previously. An optional method. A skeleton outline of a simple C program that illustrates the key elements. You never put C language statements inside a comment. Most users of a program do not see the program's instructions. Comments are messages that you insert into your C programs. Notice in the sample program. Your C compiler ignores all comments in every program.
This comment explains the filename and a little about the program. Use abundant comments. Because only people read comments. Only comment whenever code lines need explaining—in English—to the people looking at your program. If you find yourself almost repeating the C code. Comments can also share lines with other C commands.
Comments Are for You It does not matter if you use uppercase. Use comments to help explain your code. Most C programmers capitalize the first letter of sentences in comments. It prints ''C By Example" on the screen. Not every line of a C program should be commented. If you do. Example Even though you may not be familiar with C yet.
It would be much better. C program. If you were to. The section of a C program that follows is illegal because one comment resides within another: This enables the programmer to test remaining lines independently from those commented out.
In some languages. Example Listing 2. Commenting several lines out of a program. The new style of C comment is often simpler to use. The New Comment: C programs require less typing because the new style of comments requires no characters to end them. As a matter of fact. This commented-out code can sometimes be difficult to debug.
C programmers can forget to terminate the older style of comments.. A number of reasons occur for the new style's popularity: You can mix the two commenting styles if you wish. The opening brace begins the first and only block of this program.
Here are the three lines that follow: As described earlier. The next two lines following the blank separating line are shown here: When this program is compiled and run. The first three lines of the program are comments: Do not expect to become a C expert just by completing this section—that is what the rest of the book is for. The main function does not need to be the first one. This is not the only comment in the program. Studying the Sample Program Now that you have an overview of a C program.
Notice that the new comments can appear by themselves on a line or anywhere to the right of a statement. C programs often contain more than one function.
A comment in the new style must be the final item on the line. C Variables Variables have characteristics. Other information you might want to include is optional depending on the goals of your program. If two variables have the same name. To declare a variable. You declare all C variables at the top of whatever block of code needs them. Their names must begin with a letter of the alphabet.
Variable names can be as short as a single letter or as long as 31 characters. Variable names are unique. Variable declaration requires that you inform C of the variable's name and data type. The following list of variable names are all valid: C does not know which variable to use when you request one.
TIP Spaces are not allowed in a variable name. Naming Variables Because you can have many variables in a single program. Example 1.
When you decide your program needs another variable. Do not give variables the same name as a command or built-in function. Along with not using spaces or other non-alpha numeric characters except the underscore. Use meaningful variable names.
C treats uppercase letters in variable names differently than lowercase letters.
The following are invalid variable names: Some C variable types. Table 3. Using the unsigned prefix enables them to hold positive numbers only.
For instance. Variable Types Variables can hold different types of data. C assumes no decimal point or fractional part the part to the right of the decimal point exists for the variable's value. Declaring Variables There are two places where you can declare a variable: A very large number of types are possible in C. You can append the prefix long to make some of them hold larger values than they would otherwise hold. Declaration Name Type char Character unsigned char Unsigned character signed char Signed character same as char int Integer unsigned int Unsigned integer signed int Signed integer same as int short int Short integer unsigned short int Unsigned short integer signed short int Signed short integer same as short int long Long integer long int Long integer same as long signed long int Signed long integer same as long int unsigned long int Unsigned long integer float Floating-point double Double floating-point long double Long double floating-point The next section more fully describes each of these types.
Chapter 5. A character variable can hold only a single character. If you want to store these values as whole numbers. This could be accomplished with the following code: You could also declare these three variables on three separate lines.
After all. But C has more data types than almost all other programming languages. C does not have a string variable. It lets the rest of the program know that you require these three character variables.
To store a string of characters. The variable's type is critical. The following statement would declare those variables: You cannot put more than a single character into a character variable. NOTE Unlike many other programming languages. The character variable is easy to understand. Suppose you want to keep track of a person's age and weight. Integers hold whole numbers. Although mathematicians may cringe at this definition.
All of the following expressions are integers: This ensures the maximum accuracy for such numbers. You might rarely use these suffixes. You can append the floating-point suffix F or the long double floating-point suffix L to constants that contain decimal points to represent a floating-point constant or a long double floating-point constant.
Without the suffix. The format of the assignment statement is the following: By specifying the suffix. If you type 63U. Assigning Values to Variables Now that you know about the C variable types. C treats it as an unsigned integer.
C interprets that integer as a long integer. If you put an L at the end of an integer. The number 63 is an integer constant. It does not treat the number as a long integer. If you use the constant 6. C knows that this number fits into a signed integer memory location.
Assign the U suffix to designate an unsigned integer constant. The variable is any variable that you declared earlier. The number 63 is. C interprets all floating-point constants numbers that contain decimal points as double floating- point constants.
You do this with the assignment statement. The expression is any variable. The suffix UL indicates an unsigned long constant. C interprets its type as the smallest type that can hold that number. C treats it as a double floating-point data type. If you want to keep track of your current age. You first declare the variables by deciding on correct types and good names for them.
Later in the program. You then assign values to them. C lets you do this. Literal Constants As with variables. In most cases. The following section of a program declares three variables. Make sure that values you assign to variables match the variable's type. If you want to assign character data to a character variable.
The initials are character constants because they are enclosed in single quotation marks. Remember that a constant does not change. Enclose all C character constants in single quotation marks. Floating-point constants are numbers that contain a fractional portion a decimal point with an optional value to the right of the decimal point. C lets you assign integer constants to variables. The only major exception to this occurs when you assign an integer to a character variable.
Integer Constants You already know that an integer is any whole number without a decimal point. Integer constants are whole numbers that do not contain decimal points. String Constants A string constant is always enclosed in double quotation marks. NOTE A string constant is any character. A single space. C knows you want it to use the sign bit as data and not as the sign. Oak Road" "x" Any string of characters between double quotation marks—even a single character between double quotation marks—is considered to be a string constant.
This keeps C from improperly interpreting positive numbers as negative numbers. If you declared an unsigned integer. Appendix A describes these concepts in more detail. A string constant is always enclosed in double quotation marks. Here are examples of string constants: You can perform math only on numbers. If you declared the same value as a signed integer. If the string constant contains only numeric digits. A character constant is any character enclosed in single quotation marks. One type of C constant.
It is easy to print string constants. Simply put the string constants in a printf function. The double quotation marks surround the string and simply inform your C compiler that it is a string constant and not another type of constant. No other printf characters you have seen. The double quotation marks are never considered part of the string constant. Here is an example of what you need to type to print a string constant to the screen: All of the alphabetic.
Figure 3. Because of this difference. You should know that the following are very different to C: Character Constants All C character literal constants should be enclosed within single quotation marks. It is one character long. This figure shows the difference in memory between 'R' as a character constant and "R" as a string constant. The following are valid C character constants: The single quotation marks are not part of the character.
Some characters. Its length is also one. C lets you represent these characters by typing their ASCII hexadecimal number inside single quotation marks.
You could do that with the following code: You find that it is A5. An array declaration always includes brackets  that declare the storage C needs to reserve for the array.
You can also assign to the character array a value at the time you declare it. All those different variable names. Because a string is simply a list of one or more characters. The authors of C realized that you need some way to store strings in variables. The array name is name.
If you have only programmed a little before. Suppose you had to keep track of the sales records of salespeople. Part VI. The age and salary are easy because there are variable types that can hold such data. Suppose you want to keep track of a person's full name. You could make up variable names and assign to each one a different salesperson's sales record.
You would write the following code to declare those two variables: An array is a list sometimes called a table of variables. This reserves a character array.
If you were to put them in an array of floating-point variables. The following declaration statement not only declares the character array. This array is 15 characters long. Introducing Arrays Almost every type of data in C has a corresponding variable type. You have no string variable to hold the name. Notice the null zero the. Figure 4. Jones" at the same time: Each of the 15 boxes of the array is called an element. The first one. As you read through this book and become more familiar with arrays and strings.
Never declare a character array or any other type of array with empty brackets. The second array. The following statement char people. At this point. Two character arrays: The one to the left contains characters.
Strings can exist in C only as string constants. Character Arrays Versus Strings In the previous section. Look at the two arrays shown in Figure 4. These arrays could be initialized with the following declaration statements: Most compilers generate an error if you attempt this. Because you did not assign the array a value when you declared it. C assumes this array contains zero elements. NOTE Strings must be stored in character arrays. Instead of a string.
IN USA. You can fax. We value your opinion and want to know what we're doing right. I welcome your comments. Please note that I cannot help you with technical problems related to the topic of this book. When you write. As the reader of this book. I might not be able to reply to every message.
I will carefully review your comments and share them with the author and editors who worked on the book. Here is a summary of those typographical conventions: These notes clarify concepts and procedures. Not only does this book contain almost sample program listings.
The chapters of this book are standalone chapters. These programs show ways that you can use C for personal finance. TIP You'll find numerous tips offering shortcuts and solutions to common problems. There is a program for every level of reader.
The final chapter contains a large. This wide variety of programs shows you that C is a very powerful language but is still easy to learn and use. In addition to typographical conventions. NOTE Special notes augment the material you read in each hour. Conventions Used in This Book This book uses several common conventions to help teach the C programming language. Many other books build only one application. Please visit the by Example Web site for code examples or additional material associated with this book: It is now time for you to turn the page and begin learning C programming—by example.
What's Next C is the basis for many languages in use today.
The cautions warn you about pitfalls that sometimes appear when programming in C. As the first chapter explains.
Reading the caution sections will save you time and trouble. After you complete the next chapter. When you test your programs. Ever since Admiral Hopper discovered that moth. What's Next Now that you've entered. All function names have parentheses following them in a C program.
In this case. The C programming designers have already written the code for the printf function. If you do not include a value. It signals the end of a block begun earlier with the opening brace. C would know when it reached the end of the program without this statement. The printf is a built-in function. Because some functions require a return statement if you are returning values. C typically returns the 0 anyway. It's important that you keep in mind that printf is not a C command.
But it is a good programming practice to put a return statement at the end of every function. The closing brace after the return does two things in this program. What's Next Although this chapter only skimmed the surface of C. C returns control to whatever was controlling the program before it started running. Sometimes these parentheses have something between them. You have seen one function already. The last two lines in the program are shown here: Many programs in this book do not include the zero.
A value of 0. As you learn more about C. This understanding will launch well into the next chapter that explains in more detail. To differentiate printf from regular C commands. Only after you can successfully specify data in a program can you properly write code that acts upon that data and processes the data appropriately. You learn this important concept in the next chapter.