Download presentation
Presentation is loading. Please wait.
Published byAlexina Snow Modified over 9 years ago
1
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input
2
A First Book of ANSI C, Fourth Edition2 Objectives Assignment Mathematical Library Functions Interactive Input Formatted Output
3
A First Book of ANSI C, Fourth Edition3 Objectives (continued) Symbolic Constants Case Study: Interactive Input Common Programming and Compiler Errors
4
A First Book of ANSI C, Fourth Edition4 3.1 Assignment The general syntax for an assignment statement is variable = operand; –The operand to the right of the assignment operator (=) can be a constant, a variable, or an expression The equal sign in C does not have the same meaning as an equal sign in algebra –length=25; is read “length is assigned the value 25” Subsequent assignment statements can be used to change the value assigned to a variable length = 3.7; length = 6.28;
5
A First Book of ANSI C, Fourth Edition5 Assignment (continued) The operand to the right of the equal sign in an assignment statement can be a variable or any valid C expression sum = 3 + 7; product =.05 * 14.6; The value of the expression to the right of = is computed first and then the calculated value is stored in the variable to the left of = Variables used in the expression to the right of the = must be initialized if the result is to make sense amount + 1892 = 1000 + 10 * 5 is invalid!
6
A First Book of ANSI C, Fourth Edition6 Assignment (continued) If width was not initialized, the computer uses the value that happens to occupy that memory space previously (compiler would probably issue a warning)
7
A First Book of ANSI C, Fourth Edition7 Programe 3.1 #include int main( ) { float length, width, area; length = 27.2; width = 13.6; area =length * width; printf(“ The length of the rectangle is %f ”, length); printf(“ \nThe width of the rectangle is %f ”, width); printf(“ \nThe area of the rectangle is %f ”,area); return 0; }
8
A First Book of ANSI C, Fourth Edition8 When program 3.1 is run, the output obtained is The length of the rectangle is 27.200000 The width of the rectangle is 13.600000 The area of the rectangle is 369.920000
9
A First Book of ANSI C, Fourth Edition9 The program begins with the keyword main and continues sequentially, statement by statement, until the closing brace. This flow of control is true for all programs. The computer works on one statement at a time, executing that statement with no knowledge of what the next statement will be. This explains why all operands used in an expression must have values assigned to them before the expression is evaluated.
10
A First Book of ANSI C, Fourth Edition10 When the computer executes the statement area =length * width; in program 3.1,it uses whatever value is stored in the variables length and width at the time the assignment is executed. If no values have been specifically assigned to these variables before they are used in the expression length * width, the computer uses whatever values happen to occupy these variables when they are referenced.
11
A First Book of ANSI C, Fourth Edition11 The computer does not “look ahead “ to see that you might assign values to these variables later in the program. When a value is assigned to a variable for the first time, the variable is said to be initialized. Subsequent assignments can, of course, be used to change the value assigned to a variable.
12
A First Book of ANSI C, Fourth Edition12 For example, assume the following statements are executed on after another: length =3.7; length =6.28; The first assignment statement causes the value 3.7 to be stored in the variable named length. If this is the first time a value is assigned to the variable, it is also correct to say that length is initialized to 3.7.
13
A First Book of ANSI C, Fourth Edition13 The second assignment statement causes the computer to assign a value of 6.28 to length. The 3.7 that was in length is overwritten with the new value of 6.28, because a variable can store only one value at a time.
14
A First Book of ANSI C, Fourth Edition14 Assignment (continued) = has the lowest precedence of all the binary and unary arithmetic operators introduced in Section 2.4 Multiple assignments are possible in the same statement a = b = c = 25; All = operators have the same precedence Operator has right-to-left associativity c = 25; b = c; a = b;
15
A First Book of ANSI C, Fourth Edition15 Implicit Type Conversions Data type conversions take place across assignment operators double result; result = 4; //integer 4 is converted to 4.0 The automatic conversion across an assignment operator is called an implicit type conversion int answer; answer = 2.764; //2.764 is converted to 2 –Here the implicit conversion is from a higher precision to a lower precision data type; the compiler will issue a warning
16
A First Book of ANSI C, Fourth Edition16 Explicit Type Conversions (Casts) The operator used to force the conversion of a value to another type is the cast operator (dataType) expression where dataType is the desired data type of the expression following the cast Example: –If sum is declared as double sum;, (int) sum is the integer value determined by truncating sum ’s fractional part
17
A First Book of ANSI C, Fourth Edition17 Assignment Operators Although only one variable is allowed immediately to the left of the equal sign in an assignment expression, the variable on the left of the equal sign can also be used on the right of the equal sign. For example, the assignment expression sum = sum +10 is valid.
18
A First Book of ANSI C, Fourth Edition18 Clearly, in an algebra equation a variable could never be equal to itself plus 10. But in C, the expression sum = sum +10 is not an equation----it is an expression that is evaluated in two major steps. The first step is to calculate the value of sum +10. The second is to store the computed value in sum.
19
A First Book of ANSI C, Fourth Edition19 See if you can determine the output of Program 3.2. Program 3.2. #include int main( ) { int sum; sum =25; printf(“ \nThe number stored in sum is %d.”, sum); sum =sum+10; printf(“ \nThe number now stored in sum is %d.”, sum); return 0; }
20
A First Book of ANSI C, Fourth Edition20 The assignment statement sum =25; tells the computer to store the number 25 in sum as shown in Figure 3.1. The first call to printf { } in program 3.2 causes the value stored in sum to be displayed by the massage the number stored in sum is 25. The second assignment statement sum =sum+10; causes the computer to retrieve the 25 stored in sum and add 10 to this number, yielding the number 35.
21
A First Book of ANSI C, Fourth Edition21 The number 35 is then stored in the variable on the left side of the equal sign, which is the variable sum. The 25 that was in sum is simply erased and replaced with the new value of 35, as known in Figure 3.2. Assignment expressions like sum =sum+10, which use the same variable on both sides of the assignment operator, can be written using the following assignment operators: += -= *= /= %=
22
A First Book of ANSI C, Fourth Edition22 For example, the expression can be written as sum+=10. Similarly, the expression price *= rate is equivalent to the expression price = price * rate
23
A First Book of ANSI C, Fourth Edition23 New Assignment Operators In using these new assignment operators it is important to note that the variable to the left of the assignment operator is applied to the complete expression on the right. For example, the expression price *= rate +1 is equivalent to the expression price = price * (rate +1), not price = price *rate +1
24
A First Book of ANSI C, Fourth Edition24 Assignment Variations sum = sum + 10 is not an equation—it is an expression that is evaluated in two major steps
25
A First Book of ANSI C, Fourth Edition25 Assignment Variations (continued)
26
A First Book of ANSI C, Fourth Edition26 Assignment Variations (continued)
27
A First Book of ANSI C, Fourth Edition27 Accumulating Assignment expressions like sum+=10 or its equivalent, sum=sum+10, are common in programming. These expressions are required in accumulating subtotals when data is entered one number at a time.
28
A First Book of ANSI C, Fourth Edition28 For example If we want to add the numbers 96, 70, 85, and 60 in calculator fashion, the following statements could be used: Statement Value in sum sum =0; 0 sum=sum+96; 96 sum=sum+70; 166 sum=sum+85; 251 sum=sum+60; 311
29
A First Book of ANSI C, Fourth Edition29 The first statement initializes sum to 0. This removes any number(“garbage” value) stored in sum that would invalidate the final total. As each number is added, the value stored in sum is increased accordingly. After completion of the last statement, sum contains the total of all the added numbers. Program 3.3 illustrates the effect of these statements by displaying sum’s contents after each addition is made.
30
A First Book of ANSI C, Fourth Edition30 Program 3.3 #include int main( ) { int sum; sum =0; printf(“ \n The value of sum is initially set to %d.”, sum); sum =sum+96; printf(“ \n sum is now %d.”, sum);
31
A First Book of ANSI C, Fourth Edition31 sum =sum+70; printf(“ \n sum is now %d.”, sum); sum =sum+85; printf(“ \n sum is now %d.”, sum); sum =sum+60; printf(“ \n The final sum is %d.”, sum); return 0; }
32
A First Book of ANSI C, Fourth Edition32 The output displayed by program 3.3 is The value of sum is initially set to 0. sum is now 96. sum is now 166. sum is now 251. The final sum is 311.
33
A First Book of ANSI C, Fourth Edition33 Although Program 3.3 is not a practical program (it is easier to add the numbers by hand), it does illustrate the subtotaling effect of repeated use of statements having the form variable=variable +newValue;
34
A First Book of ANSI C, Fourth Edition34 Counting A special type of assignment statement that is very similar to the accumulating statement is the counting statement. Counting statements have the form variable = variable +fixeNumber;
35
A First Book of ANSI C, Fourth Edition35 Counting Statements Examples of counting statements are i = i+1; n = n+1; count = count +1; j = j + 2; m = m + 2; kk = kk +3 ;
36
A First Book of ANSI C, Fourth Edition36 Increment Operator For the special case in which a variable is either increased or decreased by one, C provides two unary operators. Using the increment operator, ++, the expression variable =variable +1 can be replaced by the expression ++variable.
37
A First Book of ANSI C, Fourth Edition37 Use of the Increment Operator Expession Alternative i=i+1 ++i n=n+1 ++n count=count+1 ++count Program 3.4 illustrates the use of the increment operator.
38
A First Book of ANSI C, Fourth Edition38 Program 3.4 #include int main( ) { int count; count =0; printf(“ \n The initial value of count is %d.”, count); ++count; printf(“ \n count is now %d.”, count); ++count;
39
A First Book of ANSI C, Fourth Edition39 printf(“ \n count is now %d.”, count); ++count; printf(“ \n count is now %d.”, count); ++count; printf(“ \n count is now %d.”, count); return 0; }
40
A First Book of ANSI C, Fourth Edition40 The output displayed by Program 3.4 is The initial value of count is 0. count is now 1. count is now 2. count is now 3. count is now4.
41
A First Book of ANSI C, Fourth Edition41 When ++appears before a variable it is called a prefix increment operator. Besides appearing before a variable, the increment operator can also be applied after a variable; for example, in the expression n++. When the increment operator appears after a variable it is called a postfix increment operator.
42
A First Book of ANSI C, Fourth Edition42 ++n and n++ Both of these expressions,++n and n++, correspond to the longer expression n=n+1,but they have different effects when used in an assignment expression. For example, the expression k=++n, which uses a prefix increment operator, does two things in one expression. Initially the value of n is incremented by one and then the new value of n is assigned to the variable k.
43
A First Book of ANSI C, Fourth Edition43 Thus, the statement k=++n; is equivalent to the two statements n=n+1; /* increment n first */ k=n; /* then assign n’s value to k */
44
A First Book of ANSI C, Fourth Edition44 k=n++ The assignment expression k=n++, which uses a postfix increment operator, reverses this procedure. A postfix increment operates after the assignment is completed. Thus, the statement k=n++; first assigns the current value of n to k and then increments the value of n by one.
45
A First Book of ANSI C, Fourth Edition45 This is equivalent to the two statements k=n; /* assign n’s value to k */ n=n+1; /* then increment n */
46
A First Book of ANSI C, Fourth Edition46 The Decrement Operator C also provides a decrement operator, --. As you might expect, the expression --variable is equivalent to the expression variable=variable-1
47
A First Book of ANSI C, Fourth Edition47 Examples of The Decrement Operator Examples of the decrement operator are Expession Alternative i=i-1 --i n=n-1 --n count=count-1 --count
48
A First Book of ANSI C, Fourth Edition48 Expressions --n and n-- Just as there are prefix and postfix increment operators, C also provides prefix and postfix decrement operators. For example, both of the expressions --n and n-- reduce the value of n by one. These expressions are equivalent to the longer expression n=n-1.
49
A First Book of ANSI C, Fourth Edition49 As with the increment operator, however, the prefix and postfix decrement operators produce different results when used in assignment expressions. For example, the expression k=--n first decrements the value of n by one before assigning the value of n to k. But the expression k=n-- first assigns the current value of n to k and then reduces the value of n by one.
50
A First Book of ANSI C, Fourth Edition50 The increment and decrement operators can often be used to reduce program storage requirements and increase execution speed. For example, consider the following three statements: count=count+1; count+=1; ++count;
51
A First Book of ANSI C, Fourth Edition51 All perform the same function; However,when these instructions were compiled for execution on an IBM personal computer, the storage requirements for the executable instructions were 9, 4, and 3 bytes, respectively. Using the assignment operator, =, instead of the increment operator results in using three times the storage space for the instruction, with an accompanying decrease in execution speed.
52
A First Book of ANSI C, Fourth Edition52 3.2 Mathematical Library Functions Library Functions—black box Must include #include The argument to sqrt must be floating-point value; passing an integer value results in a compiler error –Return value is double-precision
53
A First Book of ANSI C, Fourth Edition53 Mathematical Library Functions
54
A First Book of ANSI C, Fourth Edition54 Mathematical Library Functions (continued)
55
A First Book of ANSI C, Fourth Edition55 Mathematical Library Functions (continued)
56
A First Book of ANSI C, Fourth Edition56 Mathematical Library Functions (continued) Argument need not be a single constant
57
A First Book of ANSI C, Fourth Edition57 Mathematical Library Functions (continued) The step-by-step evaluation of the expression 3.0 * sqrt(5 * 33 - 13.91) / 5 is (see next slide)
58
A First Book of ANSI C, Fourth Edition58 Mathematical Library Functions (continued)
59
A First Book of ANSI C, Fourth Edition59 Mathematical Library Functions (continued) Determine the time it takes a ball to hit the ground after it has been dropped from an 800-foot tower –time = sqrt(2 * distance/g), where g = 32.2 ft/sec2
60
A First Book of ANSI C, Fourth Edition60 Mathematical Library Functions (continued)
61
A First Book of ANSI C, Fourth Edition61 3.3 The scanf ( ) Function Data for programs that are only going to be executed once may be included directly in the program. For example, if we wanted to multiply the numbers 300.00 and.05, we could use Program 3.8.
62
A First Book of ANSI C, Fourth Edition62 Program 3.7 #include int main( ) { float num1,num2, product; num1 =300.0; num1 =.05 product=num1 *num2; printf(“%f times %f is %f”, num1, num2,product); return 0; } The output displayed by is 300.000000 times.050000 is 15.00000
63
A First Book of ANSI C, Fourth Edition63 Program 3.8 Program 3.7 can be shortened, as illustrated in Program 3.8. #include int main( ) { printf(“%f times %f is %f”, 300.0,.05,300.0*.05); return 0; }
64
A First Book of ANSI C, Fourth Edition64 Both programs, however suffer from the same problem: they must be rewritten to multiply different numbers. Both programs lack the facility for entering different numbers to be operated on.
65
A First Book of ANSI C, Fourth Edition65 Except for the practice provided to the programmer of writing, entering, and running the program, programs that do a calculation only once, on one set of numbers, are clearly not very useful. After all, it is simpler to use a calculator to multiply two numbers than to enter and run either Program 3.7 or 3.8.
66
A First Book of ANSI C, Fourth Edition66 scanf ( ) function The section presents the scanf ( ) function, which is used to enter data to a program while it is executing. Just as the printf ( ) function displays a copy of the value stored inside a variable, the scanf ( ) function allows the user to enter a value at the video screen. The value is then stored directly in a variable.
67
A First Book of ANSI C, Fourth Edition67 Like the printf ( ) function, the scanf ( ) function requires a control string as the first argument inside the function name parentheses. The control string tells the function the type of data being input and uses the same control sequences as the printf ( ) function. Unlike the control string used in a printf ( ) function, however, the control string passed to scanf ( ) typically consists of conversion control sequences only.
68
A First Book of ANSI C, Fourth Edition68 Interactive Input (continued) scanf() is used to enter data into a program while it is executing; the value is stored in a variable It requires a control string as the first argument inside the function name parentheses The control string passed to scanf() typically consists of conversion control sequences only scanf() requires that a list of variable addresses follow the control string –scanf( "%d", &num1 );
69
A First Book of ANSI C, Fourth Edition69 Interactive Input (continued)
70
A First Book of ANSI C, Fourth Edition70 scanf (“%d”,&num1 ) The statement scanf (“%d”,&num1 ); is a call to the scanf ( ) function. The conversion control sequence %d is identical to the conversion control sequence used in printf ( ) in that it tells the scanf ( ) function that it will be dealing with an integer number. The address operator & in front of the variable num1 is required for scanf ( ).
71
A First Book of ANSI C, Fourth Edition71 When a statement such as scanf (“%d”,&num1 ) ; is encountered, the computer stops program execution and continuously scans the keyboard for data (scanf is short for scan function). When a data item is typed, the scanf ( ) function stores the item using the address it was given. The program then continues execution with the next statement after the call to scanf ( ). To see this, consider Program 3.9.
72
A First Book of ANSI C, Fourth Edition72 Program 3.9 #include int main( ) { float num1, num2, product; printf(“please type in a number:”); scanf (“%f”,&num1); printf(“please type in another number:”); scanf (“%f”,&num2); product =num1*num2; printf(“%f times %f is %f”, num1, num2,product); return 0; }
73
A First Book of ANSI C, Fourth Edition73 The following sample run was made using Program 3.9. please type in a number: 300. please type in another number:.05 300.000000 times.050000 is 15.000000
74
A First Book of ANSI C, Fourth Edition74 Interactive Input (continued) This statement produces a prompt Address operator (&)
75
A First Book of ANSI C, Fourth Edition75 The first call to printf ( ) in Program 3.9 produces a prompt, which is a message that tells the person at the screen what should be typed. In this case the user is told to type a number. The computer then executes the next statement, which is a call to scanf ( ). The scanf ( ) function puts the computer into a temporary pause (or wait) state for as long as it takes the user to type a value. Then the user signals the scanf ( ) function by pressing the ENTER key after the value has been typed..
76
A First Book of ANSI C, Fourth Edition76 The entered value is stored in the variable, num1, whose address was passed to scanf ( ), and the computer is taken out of its paused state. Program execution then proceeds with the next statement, which in Program 3.9 is another call to printf ( ). This call causes the next massage to be displayed. The second call to scanf ( ) again puts the computer into a temporary wait state while the user types a second value. This second number is stored in the variable num2
77
A First Book of ANSI C, Fourth Edition77 scanf (“%f %f”,&num1,&num2); In Program 3.9, each call to scanf ( ) is used to store one value to a variable. The scanf ( ) function, however, can be used to enter and store as many values as there are conversion control sequences in the control string.
78
A First Book of ANSI C, Fourth Edition78 For example The statement scanf (“%f %f”,&num1,&num2); results in two values being read from the terminal and assigned to the variables num1 and num2. If the data entered at the terminal was 0.052 245.79 the variables num1 and num2 would contain the values 0.052 and 245.79, respectively.
79
A First Book of ANSI C, Fourth Edition79 The space in the control string between the two conversion control sequences, “%f %f”, is strictly for readability. The control string “%f %f” would work equally well. When actually entering numbers such as 0.052 and 245.79, however, you must leave at least one space between the numbers, regardless of which control string, “%f %f” or “%f %f”, is used.
80
A First Book of ANSI C, Fourth Edition80 The space between the entered numbers clearly indicates where one number ends and the next begins. Inserting more than one space between numbers has no effect on scanf ( ).
81
A First Book of ANSI C, Fourth Edition81 scanf(“%c%c%c”,&ch1,&ch2,&ch3) The only time at a space can affect the value being entered is when scanf ( ) is expecting a character data type. For example, the statement scanf (“%c%c%c”,&ch1,&ch2,&ch3); causes scanf ( ) to store the next three characters typed in the variables ch1, ch2, and, ch3, respectively.
82
A First Book of ANSI C, Fourth Edition82 If you type x y z, then x is stored in ch1, a blank is stored in ch2, and y is stored in ch3. If, however, the statement scanf (“%c %c %c”, &ch1, &ch2, &ch3); was used, scanf ( ) looks for three characters, each character separated by exactly one space.
83
A First Book of ANSI C, Fourth Edition83 Any number of scanf ( ) function calls may be made in a program, and any number of values may be input using a single scanf ( ) function. Just be sure that a conversion control sequence is used for each value to be entered and that the address operator is used in front of the variable name where the value is to be stored. The conversion control sequences used in a scanf ( ) control string are the same as those used in printf ( ) calls, with one caution.
84
A First Book of ANSI C, Fourth Edition84 In printing a double precision number using printf ( ), the conversion control sequences for a floating point variable, %f, can be used. This is not true when using scanf ( ). If a double precision number is to be entered, the conversion control sequences %lf must be used.
85
A First Book of ANSI C, Fourth Edition85 The scanf ( ) function, like the printf ( ) function, does not test the data type of the values being entered. It is up to the user to ensure that all variables are declared correctly and that any numbers entered are of the correct type. However, scanf ( ) is “clever” enough to make a few data type conversions.
86
A First Book of ANSI C, Fourth Edition86 For example, if an integer is entered in place of a floating point or double precision number, the scanf ( ) function automatically supplies a decimal point at the end of the integer before storing the number. Similarly, if a floating point or double precision number is entered when an integer is expected, the scanf ( ) function only uses the integer part of the number.
87
A First Book of ANSI C, Fourth Edition87 For example, assume the following number are typed in response to the function call scanf (“%f %d %f”,&num1,&num2, &num3);. 56 22.879 33.923 scanf ( ) converts the 56 to 56.0 and stored this value in the variable num1. The function continues scanning the input, expecting an integer value.
88
A First Book of ANSI C, Fourth Edition88 As far as scanf ( ) is concerned, the decimal point after the 22 in the number 22.879 indicates the end of an integer and the start of a decimal number. Thus, the number 22 is stored in num2. Continuing to scan the typed input, scanf ( ) takes the.879 as the next floating point number and stores this value in num3.
89
A First Book of ANSI C, Fourth Edition89 As far as scanf ( ) is concerned, 33.923 is extra input and therefore it is ignored until the next scanf ( ), if any, is encountered. However, if you do not initially type enough data, the scanf ( ) function will continue to make the computer pause until sufficient data has been entered.
90
A First Book of ANSI C, Fourth Edition90 Caution: The Phantom Newline Character Seemingly strange results are sometimes obtained when the scanf ( ) function is used to accept characters. To see how this can occur, consider Program 3.10, which uses scanf ( ) to accept the next character entered at the keyboard, storing it in the variable fkey.
91
A First Book of ANSI C, Fourth Edition91 Program 3.10 #include int main( ) { char fkey, skey ; printf(“Type in a character:”); scanf (“%c”,&fkey); printf(“The keystroke just accepted is %d”, fkey); printf(“\nType in another character:”); scanf (“%c”,&skey); printf(“The keystroke just accepted is %d”, skey); return 0; }
92
A First Book of ANSI C, Fourth Edition92 When Program 3.10 is run, the character entered in response to the prompt Type in a character : is stored in the character variable fkey. The decimal code for the character is displayed by the second function call. The following sample run illustrates this: Type in a character: m The keystroke just accepted is 109 Type in another character : The keystroke just accepted is 10
93
A First Book of ANSI C, Fourth Edition93 The reason for this will soon become apparent. When you type m, you usually press two keys, the m key and the ENTER key. On most computer systems these two characters are stored in a temporary holding area called a buffer immediately after they are pressed.
94
A First Book of ANSI C, Fourth Edition94 The first key pressed, m in this case, is taken from the buffer and stored in fkey. This, however, still leaves the code for the ENTER key in the buffer. Any subsequent call to scanf ( ) for a character input will automatically pick up the code for the ENTER key as the next character.
95
A First Book of ANSI C, Fourth Edition95 The following is a sample run for Program 3.10: Type in a character: m The keystroke just accepted is 109 Type in another character: The keystroke just accepted is 10
96
A First Book of ANSI C, Fourth Edition96 Remember that every key has a numerical code, including the ENTER, SPACE, ESCAPE, and CONTROL keys. These keys generally have no effect when entering numbers, because scanf ( ) ignores them as leading or trailing whitespace input with numerical data. Nor do these keys affect the entry of a single character requested as the first user data to be input. Only when a character is requested after the user has already input some other data, as in Program 3.10, does the usually invisible ENTER key become noticeable.
97
A First Book of ANSI C, Fourth Edition97 There is a quick solution to the problem of having the ENTER key accepted as a legitimate character input. All we have to do is accept the ENTER key, store it as a character variable, and then just not use it. Program 3.11 illustrates this technique. The ENTER key is accepted along with the first character typed. This clears the computer’s buffer and prepares the way for the character input.
98
A First Book of ANSI C, Fourth Edition98 Program 3.11 #include int main( ) { char fkey, skey ; printf(“Type in a character:”); scanf (“%c%c”,&fkey, &skey); /* the enter code goes to skey */ printf(“The keystroke just accepted is %d”, fkey); printf(“\nType in another character:”); scanf (“%c”,&skey); /*accept another code */ printf(“The keystroke just accepted is %d”, skey); return 0; }
99
A First Book of ANSI C, Fourth Edition99 From the use’s standpoint, the ENTER key has no effect except to signal the end of each character in input. The following is a sample run for Program 3.11. Type in a character: m The keystroke just accepted is 109 Type in another character: b The keystroke just accepted is 98
100
A First Book of ANSI C, Fourth Edition100 A First Look at User-Input Validation
101
A First Book of ANSI C, Fourth Edition101 A First Look at User-Input Validation (continued) As written, Program 3.12 is not robust The problem becomes evident when a user enters a non-integer value Enter three integer numbers: 10 20.68 20 The average of 10, 20, and -858993460 is - 286331143.333333 Handling invalid data input is called user-input validation –Validating the entered data either during or immediately after the data have been entered –Providing the user with a way of reentering any invalid data
102
A First Book of ANSI C, Fourth Edition102 3.4 Formatted Output The format of number displayed by printf ( ) can be controlled by field width specifiers included as part of each conversion control sequence. For example, the statement printf ( “The sum of %3d and %4d is %5d.”, 6, 15, 21); causes the printout The sum of 6 and 15 is 21. The number 3.4.and 5 in the control string are the field width specifiers.
103
A First Book of ANSI C, Fourth Edition103 Program 3.13 Program 3.13 illustrates how a column of integer would align in the absence of field width specifiers. # include int main ( ) { printf ( “\n%d”, 6); printf ( “\n%d”, 18); printf ( “\n%d”, 124); printf ( “\n---“); printf ( “\n%d”, 6+18+124); return 0; }
104
A First Book of ANSI C, Fourth Edition104 Formatted Output 6 18 124 --- 148 Output is not aligned
105
A First Book of ANSI C, Fourth Edition105 The output of program 3.13 is 6 18 123 --- 148 Since no field widths are given, the printf ( ) function allocates enough space for each number as it is received.
106
A First Book of ANSI C, Fourth Edition106 Program 3.14 # include int main ( ) { printf ( “\n%3d”, 6); printf ( “\n%3d”, 18); printf ( “\n%3d”, 124); printf ( “\n---“); printf ( “\n%3d”, 6+18+124); return 0; }
107
A First Book of ANSI C, Fourth Edition107 The output of program 2.2 6 18 124 --- 148
108
A First Book of ANSI C, Fourth Edition108 Formatted Output (continued) 6 18 124 --- 148 Field width specifier
109
A First Book of ANSI C, Fourth Edition109 The statement printf ( “ ︱ %10.3f ︱ ”, 25.67); causes the printout ︱ 25.670 ︱ The bar character, ︳,in the example is used to marked the beginning and the end of the display, The field width specifier 10.3 tells printf ( ) to display the number in a total field of 10, which includes one decimal point and three digits to the right of the decimal point.
110
A First Book of ANSI C, Fourth Edition110 Format Modifiers Left Justification. To force the output to left-justify the display, a minus sign (-) format modifier can be used. For example, the statement printf ( “ ︱ %-10d ︱ ”, 59); causes the display ︱ 59 ︱ Notice that 59 is printed at the beginning of the field rather than at the end of the field.
111
A First Book of ANSI C, Fourth Edition111 Explicit Sign Display. To force both positive and negative signs to be displayed, a puls (+) format modifier must be used. printf (“ ︱ %+10d ︱ ”,59); the display ︱ +59 ︱
112
A First Book of ANSI C, Fourth Edition112 Format modifiers Format modifiers may be combined. For example, %-+10d would causes an integer number to both display its sign and be left-justified in a field width of 10 spaces. The order of the format modifiers is not critical %+-10d is the same
113
A First Book of ANSI C, Fourth Edition113 Other Number Bases To have the value of an integer displayed in either a base 8(octal) or base 16 (hexadecimal) form requires the use of the coversion control sequences %o and %x,respectively.
114
A First Book of ANSI C, Fourth Edition114 A program to illustrate output conversion Program 3.15 #include int main ( ) /* a program to illustrate output conversion */ { printf ( “The decimal (base 10) value of 15 is %d.”,15); printf (“\nThe octal (base o) values of 15 is %o.”, 15); printf (“\nThe hexadecimal (base 16) values of 15 is %x.”,15); return 0; }
115
A First Book of ANSI C, Fourth Edition115 The output produced by program 3.15 is The decimal (base 10) value of 15 is 15. The octal (base 8) value of 15 is 17. The hexadecimal (base 16) value of 15 is f.
116
A First Book of ANSI C, Fourth Edition116 Other Number Bases [Optional] The decimal (base 10) value of 15 is 15. The octal (base 8) value of 15 is 17. The hexadecimal (base 16) value of 15 is f.
117
A First Book of ANSI C, Fourth Edition117 The number in C To designate an octal integer constant, the number must have a leading zero. Hexadecimal numbers are denoted using a leading 0x. To force both octal and hexadecimal numbers to be printed with a leading 0 and 0x, respectively, the # form modifier must be used.
118
A First Book of ANSI C, Fourth Edition118 Program 3.16 # include int main ( ) { printf ( “ The decimal value of 025 is %d.\n”, 025); printf ( “ The decimal value of 0x37 is %d.\n”, 0x37); return 0; } The output is The decimal value of 025 is 21. The decimal value of 0x37 is 55.
119
A First Book of ANSI C, Fourth Edition119 printf ( “The octal value of decimal 21 is %#o”,21); produces the display The octal value of decimal 21 is 025. Without # between % and o, the display would be 25. without 0.
120
A First Book of ANSI C, Fourth Edition120 Similarly, the statement printf ( “ The hexadecimal value of decimal 55 is %#x”,55); produces the display The hexadecimal value of decimal 55 is 0x37. Without # between % and x, the display would be 37, without 0x.
121
A First Book of ANSI C, Fourth Edition121 Program 3.17 # include int main ( ) { printf ( “ The decimal value of the letter %c is %d.”, ‘a’, ‘a’); printf ( “ \nThe octal value of the letter %c is %o.”, ‘a’, ‘a’); printf ( “ \nThe hex value of the letter %c is %x.”, ‘a’, ‘a’); return 0; } The output is The decimal value of the letter a is 97. The octal value of the letter a is 141. The hex value of the letter a is 61.
122
A First Book of ANSI C, Fourth Edition122 Other Number Bases (continued) The decimal value of the letter a is 97. The octal value of the letter a is 141. The hex value of the letter a is 61.
123
A First Book of ANSI C, Fourth Edition123 Formatted Output (continued)
124
A First Book of ANSI C, Fourth Edition124 3.5 Symbolic Constants Literal data is any data within a program that explicitly identifies itself. For example, the constants 2 and 3.1416 in the assignment statement circum= 2 * 3.1416 *radius; are also called literals because they are literally included directly in the statement. Additional examples of literals are contained in the following C assignment statements.
125
A First Book of ANSI C, Fourth Edition125 See if you can identify them. perimeter=2 * length * width; y=(5 * p)/7.2; salestax=0.05 * purchase; The literals are the numbers 2, 5 and 7.2, and 0.05 in the first, second and third statements, respectively.
126
A First Book of ANSI C, Fourth Edition126 The same literal often appears many times in the same program. For example, in a program used to determine bank interest charges, the interest rate would typically appear in different places throughout the program. Similarly, in a program used to calculate taxes, the tax rate might appear in many individual instructions. If either the interest rate or tax rate change, the programmer would have the cumbersome task of changing the literal value everywhere it appears in the program.
127
A First Book of ANSI C, Fourth Edition127 Multiple changes, however, are subject to error-if just one rate value is overlooked and not changed, the result obtained when the program is run will be incorrect. Literal values that appear many times in the same program are referred to by programmers as magic numbers. By themselves the numbers are quite ordinary, but in the context of a particular application they have a special (“magical”) meaning.
128
A First Book of ANSI C, Fourth Edition128 To avoid the problem of having a magic number spread throughout a program, C provides the programmer with the capability to define the value once by equating the number to a symbolic name. Then, instead of using the number throughout the program, the symbolic name is used instead. If the number ever has to be changed, the change need only be made once at the point where the symbolic name is equated to the actual number value. Equating numbers to symbolic names is accomplished using a # define statement.
129
A First Book of ANSI C, Fourth Edition129 Two such statements are #define SALESTAX 0.05 no semicolon #define PI 3.1416 no semicolon
130
A First Book of ANSI C, Fourth Edition130 These two statements are called either #define or equivalence statements. The first #define statement equates the value 0.05 to the symbolic name SALESTAX, while the second #define statement equates the number 3.1416 to the symbolic name PI. Other terms for symbolic names are named constants and symbolic constants. We shall use these terms interchangeably.
131
A First Book of ANSI C, Fourth Edition131 It is common in C to use all uppercase letters for symbolic constants. Then whenever a programmer sees all uppercase letters in a program, he or she will know the name is a symbolic constant defined in a #define statement, and not a variable name declared in a declaration statement. The symbolic constants defined above can be used in any C statement in place of the numbers they represent.
132
A First Book of ANSI C, Fourth Edition132 For example, the assignment statements circum= 2 * PI *radius; amount=SAlESTAX * purchase; are both valid. These statements must, of course, appear after the named constants are defined.
133
A First Book of ANSI C, Fourth Edition133 Usually, all #define statements are placed at the top of a file, before any functions, including main ( ). #define and #include statements may be freely intermixed. Thus, in Program 3.18, the #include statement could have been placed above the #define statement.
134
A First Book of ANSI C, Fourth Edition134 Program 3.18 #define SALESTAX 0.05 #include int main( ) { float amount, taxes, total; printf(“\n Enter the amount purchased: “); scanf(“%f”, &amount); taxes= SALESTAX * amount; total= amount + taxes; printf(“The sales tax is $%4.2f”,taxes); printf(“\nThe total bill is $5.2f”, total); return 0; }
135
A First Book of ANSI C, Fourth Edition135 The following sample run was made using Program 3.18. Enter the amount purchased: 36.00 The sales tax is $1.80 The total bill is $37.80
136
A First Book of ANSI C, Fourth Edition136 Whenever a named constant appears in an instruction it has the same effect as if the literal value it represents was used. Thus, SALESTAX is simply another way of representing the value 0.05. Since SALESTAX and the number 0.05 are equivalent, the value of SALESTAX may not subsequently be changed by the program.
137
A First Book of ANSI C, Fourth Edition137 An instruction such as SALESTAX=0.06; is meaningless, because SALESTAX is not a variable. Since SALESTAX is only a stand-in for the value 0.05, this statement is equivalent to writing the invalid statement 0.05=0.06;
138
A First Book of ANSI C, Fourth Edition138 Notice also that #define statements do not end with a semicolon. The reason for this is that #define statements are not processed by the regular C complier used to translate C statements into machine language. The # sign is a signal to a C preprocessor. This preprocessor screens all program statements when a C program is complied. When the preprocessor encounters a # sign, it recognizes an introduction to itself.
139
A First Book of ANSI C, Fourth Edition139 The word define tells the preprocessor to equate symbolic constant in the statement with the information or data following it. In the case of a statement like #define SALESTAX 0.05, the word SALESTAX is equated to the value 0.05. The preprocessor then replaces each subsequent occurrence of the word SALESTAX in the C program with the value 0.05.
140
A First Book of ANSI C, Fourth Edition140 Symbolic Constants (continued) # sign is a signal to a C preprocessor
141
A First Book of ANSI C, Fourth Edition141 Case Study: Interactive Input
142
A First Book of ANSI C, Fourth Edition142 Case Study: Interactive Input (continued)
143
A First Book of ANSI C, Fourth Edition143 Common Programming Errors Forgetting to assign initial values to all variables before the variables are used in an expression Calling sqrt() with an integer argument Forgetting to use the address operator, &, in front of variable names in a scanf() function call Not including the correct control sequences in scanf() function calls for the data values that must be entered Including a message within the control string passed to scanf()
144
A First Book of ANSI C, Fourth Edition144 Common Programming Errors (continued) Terminating a #define command to the preprocessor with a semicolon Placing an equal sign in a #define command when equating a symbolic constant to a value Using the increment and decrement operators with variables that appear more than once in the same expression Being unwilling to test a program in depth
145
A First Book of ANSI C, Fourth Edition145 Common Compiler Errors
146
A First Book of ANSI C, Fourth Edition146 Common Compiler Errors (continued)
147
A First Book of ANSI C, Fourth Edition147 Summary Arithmetic calculations can be performed using assignment statements or mathematical functions The assignment symbol, =, is an operator C provides the +=, -=, *= and /= assignment operators The increment operator, ++, adds 1 to a variable The decrement operator, --, subtracts 1 from a variable C provides library functions for calculating square root, logarithmic, and other mathematical computations
148
A First Book of ANSI C, Fourth Edition148 Summary (continued) Mathematical functions may be included within larger expressions scanf() is a standard library function used for data input When a scanf() function is encountered, the program temporarily suspends further statement execution until sufficient data has been entered for the number of variable addresses contained in the scanf() function call
149
A First Book of ANSI C, Fourth Edition149 Summary (continued) It is good programming practice to display a message, prior to a scanf() function call, that alerts the user as to the type and number of data items to be entered Field width specifiers can be included with conversion control sequences to explicitly specify the format of displayed fields Each compiled C program is automatically passed through a preprocessor Expressions can be made equivalent to a single identifier using the preprocessor #define command
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.