Practical c programming third edition free download
The number 8. If you try to add 1 to , you will get an overflow error. Computers have similar limits. The limits on integers are implementation dependent, meaning they change from computer to computer.
Calculators use decimal digits Computers use binary digits 0 -1 called bits. Eight bits make a byte. The number of bits used to hold an integer varies from machine to machine. Numbers are converted from binary to decimal for printing. On most UNIX machines, integers are 32 bits 4 bytes , providing a range of 2 31 -1 to On the PC, most compilers use only 16 bits 2 bytes , so the range is 2 15 -1 to These sizes are typical. The standard header file limits. See Chapter 18, for more information on header files.
Programs that depend on an integer being a specific size say 32 bits frequently fail when moved to another machine. What will be the result when it is run on a PC? Click here for the answer Section 4. The semicolon ; ends the statement.
Declarations create space for variables. Figure 4 -1 A illustrates a variable declaration for the variable answer. We have not yet assigned it a value so it is known as an uninitialized variable.
The question mark indicates that the value of this variable is unknown. Declaration of answer and assigning it a value Assignment statements are used to give a variable a value. So the variable answer gets t h e value 12 as illustrated in Figure 4 -1B. It literally means: Compute the expression and assign the value of that expression to the variable. In C, the operator is used for assignment.
In Example , we use the variable term to store an integer value that is used in two later expressions. How can we tell if it is working or not? We need some way of printing the answers. This is called the parameter list. The general form of the printf statement is: printf format, expression-1, expression-2, Figure 4 -2 shows how the elements of the printf statement work together to generate the final result. Example 4 -3 shows a program that computes term and prints it via two printf functions.
C will not verify this. Actually, the GNU gcc compiler will check printf arguments, if you turn on the proper warnings. If too many expressions are supplied, the extra ones will be ignored.
If there are not enough expressions, C will generate strange numbers for the missing expressions. The numbers 5. C uses the decimal point to distinguish between floating-point numbers and integers.
Floating -point numbers must contain a decimal point. Floating -po int numbers include: 3. Although you could omit digits before the decimal point and specify a number as. A similar rule applies to A floating-point zero should be written as 0. This limit varies widely from computer to computer. Floating-point accuracy will be discussed further in Chapter To print the expression 1.
There is a vast difference between an integer divide and a floating-point divide. In an integer divide, the result is truncated any fractional part is discarded.
If either the d ivisor or the dividend is a floating-point number, a floating -point divide is executed. So Several examples appear in Table 4 C will automatically perform the conversion from integer to floating point.
A similar conversion is performed when a floating -point number is assigned to an integer. Question : Why is the result of Example 4 -4 0.
What must be done to this program to fix it? Your results may vary. See Example 4 It is used to signal that a special character follows. It causes the output device to go to the beginning of the next line similar to a return key on a typewriter. Table summarizes these special cha racters. A good way to remember the difference between these two types of quotes is to remember that single characters are enclosed in single quotes.
Strings can have any number of characters including one , and they are enclosed in double quotes. Example 4 -7 reverses three characters. The zip code is larger than , so it is mangled, an d the result is This problem can be fixed by using a long int instead of just an int. The various types of integers will be discussed in Chapter 5. The number 1 and the number 3 are both integers, so this question is an integer divide.
Fractions are truncated in an integer divide. C does not check to make sure printf is given the right number of parameters. Because no value was specified, C makes one up. The printf function has no way of checking its parameters for type. So if you give the function a floating -point number, but the format specifies an integer, the function will treat the number as an integer and print unexpected results.
Exercise : Write a progra m to compute the area and perimeter of a rectangle with a width of three inches and a height of five inches. What changes must be made to the program so that it works for a rectangle with a width of 6.
Exercise : Write a program to print "HELLO" in big block letters; each letter should have a height of seven characters and width of five characters. Arrays, Qualifiers, and Reading Numbers That mysterious independent variable of political calculations, Public Opinion.
That process is fine for a small number of bricks, but what happens when we want to construct something larger? We would like to point to a stack of bricks and say, "That's for the left wall. That's brick 1, brick 2, brick An array is a set of consecutive memory locations used to store data.
Each item in the array is called an element. The number of elements in an array is called the dimension of the array.
To reference an element of an array, you use a number called the index—the number inside the square brackets [ ]. C is a funny language that likes to start counting at 0. So, our three elements are numbered to 2. Example 5 -1 computes the total and average of five numbers. C does not have a built-in string type; instead, strings are created out of character arrays. In fact, strings are just character arrays with a few restrictions. Note that we had to allocate one character for the end-of-string marker.
String constants consist of text enclosed in double quotes "". You may have noticed that the first parameter to printf is a string constant. The size of the array is 50, but the length of the string is 3. Any string up to 49 characters long can be stored in string. One character is reserved for the NUL that indicates end-o f-string. String and character constants are very different. Strings are surrounded by double quotes " and characters by single quotes '.
So "X" is a one-character string, while 'Y' is just a single character. The character 'Y' takes up one byte. There are several standard routines that work on string variables, as shown in Table The program works by initializing the variable first to the first name Steve. The last name Oualline is put in the variable last.
Then strcat is used to add a space. We call strcat again to tack on the last name. If we get a name more than 99 characters long, our program will mess up. What actually happens is that you write into memory that you shouldn't access. This access can cause your program to crash, run normally and give incorrect results, or behave in other unexpected ways.
The arguments are: name is the name of a character array. The line including the end -o f-line character is read into this array. The sizeof function provides a convenient way of limiting the number of characters read to the maximum numbers that the variable can h old.
This function will be discussed in more detail in Chapter In this case, the file is the standard input or keyboard. Other files are discussed i n Chapter Example 5 -4 reads a line from the keyboard and reports its length. Where's the extra character coming from? Suppose we wanted to change our name program to ask the user for his first and last name.
Example 5 -5 shows how we could write the program. What happened? The fgets function gets the entire line, including the end-of-line. We must get rid of this character before printing. We need a general algorit hm to solve this problem. The length of this string is the index of the end-o f-string null character. The character before it is the one we want to get rid of.
Click here for the answer Section 5. We want to read numbers as well. The function scanf works like printf, except that scanf reads numbers instead of writing them. The function scanf is notorious for its poor end-o f-line handling, which makes scanf useless for all but an expert. Instead, we use fgets to read a line of input andsscanf to convert the text into numbers. The name sscanf stands for "string scanf". This symbol is used to indicate that sscanf will change the value of the associated variables.
For information on why we need the ampersand, see Chapter In some cases a random variable or instruction will be changed. In Example , we use sscanf to get and then double a number from the user. This omission is intentional because we do not want the computer to print a newline after the prompt.
For some strange reason, the compiler refuses to believe that we declared the variable width. The declaration is right there on line 2, just after the definition of height. Why isn't the compiler seeing it? If too many numbers are present, a warning will be issued. If an insufficient amount of n umbers are present, C will initialize the extra elements to 0.
If no dimension is given, C will determine the dimension from the number of elements in the initialization list. A set of brackets [ ] encloses each dimension. Some languages, like BASIC [1] , go to great lengths to completely isolate the user fro m the details of how the processor works. This simplification comes at a great loss of efficiency. C lets you give detailed information about how the hardware is to be used. BASIC provides the programmer with only one numeric type.
C allows the programmer to specify many different flavors of integers, so that the programmer can make best use of hardware. The type specifier int tells C to use the most efficient size for the machine you are using for the integer. This can be two to four bytes depending on the machine. Some less common machines use strange integer sizes such as 9 or 40 bits. Sometimes you need extra digits to store numbers larger than those allowed in a normal int.
The long qualifier informs C that we wish to allocate extra storage for the integer. If we are going to use small numbers and wish to reduce storage, we use the qualifier short. Character variables use 1 byte. They can also be used for numbers in the range of to signed char or to unsigned char. Unlike integers, they do not default to signed ; the default is compiler dependent.
You must read the number into an integer and then use an assignment statement. The most compact integers have type char. They also have the most li mited range. They are also useful for things that can never be negative, like counters and indices.
The flavor of number you use will depend on yo ur program and storage requirements. Double-precision variables give the programmer many times the range and precision of single-precision float variables. The qualifier long double denotes extended precision. On some systems, this is the same as double; on others, it offers additional precision. All types of floating -point numbers are a lways signed. Table 5 -3 contains the printf and sscanf conversions for floating-point numbers. On some machines, single-precision, floating-point instructions execute faster but less accurately than double -precision instructions.
Double -precision instructions gain accuracy at the expense of time and storage. In most cases, float is adequate; however, if accuracy is a problem, switch to double.
See Chapter The keyword const indicates a variable that never changes. Constants must be initialized at declaration time and can never be changed. For example, if we tried to reset the value of PI to 3. These strings are decimal base 10 numbers: or Computers deal with binary base 2 numbers: The octal base 8 system easily converts to and from binary.
Thus, can be written as 10 and changed to the octal Hexadecimal base 16 numbers have a similar conversion; only 4 bits are used at a time.
The C language has conventions for representing octal and hexade cimal values. Leading zeros are used to signal an octal constant. For example, is octal or 83 decimal. Starting a number with "0x" indicates a hexadecimal base 16 constant. So, 0x15 is 21 decimal. Table 5 -4 shows several numbers in all three bases. Frequently, the programmer wants to increment increase by 1 a variable. A side effect is an operation that is performed in addition to the main operation executed by the statement.
The second statement assigns to result the value of size main operation and increments size side effect. But in what order are these processes performed? There are four possible answers. The answer is compile r-dependent and varies from computer to computer. If we don't write code like this, then we don't have to worry about such questions.
The correct answer is number 2: the increment occurs before the assignment. However, number 4 is a much better answer.
Th e main effects of C are confusing enough without having to worry about side effects. Some programmers value compact code very highly. This attitude is a holdover from the early days of computing when storage cost a significant amount of money. I believe that the art of programming has evolved to the point where clarity is much more valuable than compactness. Great novels, which a lot of people enjoy reading, are not written in shorthand.
The programmer doesn't read this statement, but rather decodes it. Which form should you use? Actually in C your choice doesn't matter. Multiply value by 5, and add 1 to value. Multiply value by 3, and add 1 to value. Add the results of the two multiplications together. Steps 1 and 2 are of equal priority unlike in the previous e xample so the compiler can choose the order of execution. Suppose the compiler executes step 1 first, as shown in Figure 5 Expression evaluation method 1 Or suppose the compiler executes step 2 first, as shown in Figure 5 By using the second method, we get a result of The result of this expression is ambiguous.
Depending on how the compiler was implemented, the result may be 11 or Even worse, some compilers change the behavior if optimization is turned on. So what was "working" code may break when optimized. We will get into more trouble in Chapter The value of this operator is the value of the last expressions.
As a result x,y is equivalent to y; and array[y] is actually a pointer to row y of the array. Because pointers have strange values, the printf outputs strange results. See Chapter 17 , and Chapter The comment continues onto the next line and engulfs the declaration, as shown in Example Comment Answer Consider another minor problem with this program. If width and height are both odd, we get an answer that's slightly wrong.
How would you correct this error? Exercise : Write a program to calculate the volume of a sphere. Exercise : Write a program that prints the perimeter of a rectangle given its height and width. Decision and Control Statements Once a decision was made, I did not worry about it afterward. Decision and control statements are needed. They specify the order in which statements are to be executed. So far, we have constructed linear programs, that is, programs that execute in a straight line, one statement after another.
In this chapter, we will see how to change the control flow of a program with branching statements and looping statements. Branching statements cause one section of code to be executed or not executed, depending on a conditional clause.
Looping statements are used to repeat a section of code a number of times or until some condition occurs. The general form of the if statement is: if condition statement; If the condition is true nonzero , the statement will be executed. If the condition is false 0 , the statement will not be executed. For example, suppose we are writing a billing program. At the end, if the customer owes us nothing or has a credit owes us a negative amount , we want to print a message.
One of the most common problems the C programmer faces is mixing them up. If it is false 0 , the second statement is executed. In our accounting example, we wrote out a message only if nothing was owed. There are two if statements and one else.
Which if does the else belong to? It belongs to if 1. It belongs to if 2. If you never write code like this, don't worry about this situation. The correct answer is "c. We should write code as clearly and simply as possible. These omissions lead to the following confusing code: if strcmp string1, string2 printf " Unfortunately, the obvious is wrong. If the strings are equal, strcmp returns 0, and the printf is not executed.
Because of this backward behavior of strcmp , you should be very careful in your use of strcmp and always comment its use. It also helps to put in a comment explaining what you're doing. For example, loops are used to count the number of words in a document or to count the number of accounts that have past-due balances.
The general form of a while statement is: while condition statement; The program will repeatedly execute the statement inside the while until the condition becomes false 0. If the condition is initially false, the statement will not be executed. For example, Example 6 -1 later in this chapter will compute all the Fibonacci numbers that are less than Mathematicians use this very terse style of naming variables.
In programming, terse is dangerous, so we translate these names into something verbose for C. Table shows this translation. Fibonacci execution This completes the body of the loop. The first two terms of the Fibonacci sequence are 1 and 1. We initialize our first two terms to these values. Putting it all together, we get the code in Example 6 The loop exits when the condition after the while becomes false 0.
Loops can be exited at any point through the use of a break statement. Suppose we want to add a series of numbers, but we don't know how many numbers are to be added together.
We need some way of letting the program know that we have reached the end of our list. In Example , we use the number zero 0 to signal the end-of-list. The only way to exit this loop is through a break statement. For example, if we want to modify the previous program to total only numbers larger than 0, we could write a program such as Example Programs should be clear and simple and should not hide anything.
The most important rule of programming is keep it simple. C also allows the programmer to put assignment statements in the while conditional. Click here for the answer Section 6. The problem is that C allows assignment statements inside if conditionals.
If the result was nonzero true , the if clause would be executed. Beca use the result is false , the else clause is executed and the program prints the wrong answer. For a more advanced problem, find the actual distance. This problem involves u sing the standard function sqrt. Use your help system to find out more about how to use this function.
Exercise : A professor generates letter grades using Table 6 A good exercise is to take someone else's code, such as the program that someone wrote for Chapter 6, and then modify it. The modifiers are listed in Table Note: An F is only an F. Exercise : A leap year is any year divisible by 4, unless the year is divisible by , but not Write a program to tell if a year is a leap year.
Exercise : Write a program that, given the number of hours an employee worked and the hourly wage, computes the employee's weekly pay. Count any hours over 40 as overtime at time and a half.
Programming Process It's just a simple matter of programming. Software has a life cycle. It is born, grows up, becomes mature, and finally dies, only to be replaced by a newer, younger product. Figure illustrates the life cycle of a program. Understanding this cycle is important because, as a programmer, you will spend only a small amount of time writing new code. Most programming time is spent modifying and debugging existing code.
Software does not exist in a vacuum; it must be docume nted, maintained, enhanced, and sold. In this chapter, we will take a look at a small programming project using one programmer.
Larger projects that involve many people will be discussed in Chapter Although our final code is less than lines, the principles used in its construction can be applied to programs with thousands of lines of code.
Programs start when someone gets an idea and starts to implement it. The requirement document describes, in very general terms, what is wanted. The specification is a description of what the program does. In the beginning, a preliminary specification is used to describe what the program is going to do. Later, as the program becomes more refined, so does the specification. Finally, when the program is finished, the specification serves as a complete description of what the program does.
The programmer does an overall design of the program. The design should include major algorithms, module definitions, file formats, and data structures. The next step is writing the program. This step involves first writing a prototype and then filling it in to create the full program. The programmer should design a test plan and then use it to test his program.
When possib le, the programmer should have someone else test the program. Unfortunately, very few programs work the first time. They must be corrected and tested again. The program is packaged, documented, and sent out into the world to be used. Programs are never perfect. Bugs will be found and will need correction. This step is the maintenance phase of programming. After a program has been working for a while, the users will want changes, such as more feature s or more intelligent algorithms.
At this point, a new specification is created and the process starts again. Just as file folders serve as a way of keeping papers together in a filing cabinet, directories serve as a way of keeping files together. Windows 95 goes so far as to call its directories "folders.
All the files for this program are stored in a directory named calc. As you generate more and more programs, you will probably want a more elaborate directory structure. More information on how to organize directories or folders can be found in your operating system manual. The programmer refines it into something that exactly defines the program that he is go ing to produce.
So the first step is to write a preliminary users' specification document that describes what your program is going to do and how to use it. The document does not describe the internal structure of the program or the algorithm you plan on u sing. A sample specification for our four-function calculator appears below in Calc: A Four-Function Calculator. The preliminary specification serves two purposes. First, you should give it to your boss or customer to make sure that you agree on what each of you said.
Second, you can circulate it among your colleagues and see if they have any suggestions or corrections. Any resemblance to any software living or dead is purely coincidental. The program will add, subtract, multiply, and divide simple integers. When the progra m is run, it will zero the result register and display the register's contents.
The user can then type in an operator and number. The result will be updated and displayed. A college instructor once gave his students an assignment to "write a four-function calculator. The program came with a complete user manual—written in Latin. This book teaches you not only the mechanics of programming, but also describes how to create programs that are easy to read, debug, and update.
Practical rules are stressed. The practical programmer reduces these to two:. Contrary to popular belief, most programmers do not spend most of their time creating code. Most of their time is spent modifying someone else's code. They are Xilinx and Altera. Their business is FPGA design. A novel approach to developing and applying databases with Visual C. NET clearly explains the considerations and applications in database programming with Visual C. Sidestepping the traditional approach of using large blocks of code, Ying Bai utilizes both Design Tools and Wizards provided by Visual Studio.
NET and real-time object methods to incorporate over sixty real sample database programming projects along with detailed illustrations and explanations to help readers understand the key techniques and programming technologies in database programming.
This invaluable resource features:Fundamenta Beginning C for Arduinois written for those who have no prior experience with microcontrollers or programming but would like to experiment and learn both. This book introduces you to the C programming language, reinforcing each programming structure with a simple demonstration ofhow you can use C to control the Arduino family of microcontrollers.
0コメント