Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 2 Overview of C Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.

Similar presentations


Presentation on theme: "Chapter 2 Overview of C Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University."— Presentation transcript:

1 Chapter 2 Overview of C Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of Technology

2 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-2 Arithmetic Expressions

3 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-3 Arithmetic Expressions -- Operators / and % When applied to two positive integers, the division operator (/) computes the integral part of the result of dividing its first operand by its second. If the / operator is used with a negative and a positive integer, the result may vary from one C implementation to another. –avoid using division with negative integers In m % n, the operation is undefined when n is zero and varies from one implementation to another if n is negative.

4 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-4 Arithmetic Expressions -- Operators / and % (Cont’)

5 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-5 Arithmetic Expressions -- Operators / and % (Cont’) m equals (m / n) * n (m % n) 7 equals (7 / 2) * 2 + (7 % 2) equals 3 *2+1 299 equals (299 / 100) * 100 + (299 % 100) equals 2 *100 + 99

6 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-6 Arithmetic Expressions -- Operators / and % (Cont’)

7 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-7 Arithmetic Expressions -- Operators / and % (Cont’)

8 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-8 Arithmetic Expressions -- Operators / and % (Cont’)

9 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-9 Arithmetic Expressions -- Data Type of an Expression The data type of an expression depends on the type(s) of its operands. “ace arithmetic_operator bandage” is of type int if both ace and bandage are of type int; otherwise, it is of type double. mixed-type expression –an expression with operands of different types The data type of such a mixed-type expression will be double.

10 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-10 Arithmetic Expressions -- Mixed-Type Assignment Statement When an assignment statement is executed, the expression is first evaluated; then the result is assigned to the variable listed to the left of the assignment operator (=). mixed-type assignment –the expression being evaluated and the variable to which it is assigned have different data types

11 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-11 Arithmetic Expressions -- Mixed-Type Assignment Statement (Cont’) The expression is evaluated before the assignment is made, and the type of the variable being assigned has no effect whatsoever on the expression value. E.g. If m and n are type int and p, x, and y are type double: m = 3; n = 2; p = 2.0; x = m / p; y = m / n;

12 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-12 Arithmetic Expressions -- Mixed-Type Assignment Statement (Cont’) Assignment of a type double expression to a type int variable causes the fractional part of the expression to be lost since it cannot be represented in a type int variable. E.g. x = 9 * 0.5; n = 9 * 0.5;

13 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-13 Arithmetic Expressions -- Type Conversion through Casts type cast –converting an expression to a different type by writing the desired type in parentheses in front of the expression

14 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-14 Arithmetic Expressions -- Type Conversion through Casts (Cont’)

15 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-15 Arithmetic Expressions -- Expressions with Multiple Operators unary operator –an operator with one operand binary operator –an operator with two operands

16 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-16 Arithmetic Expressions -- Expressions with Multiple Operators (Cont’) Rules for Evaluating Expressions –a. Parentheses rule: All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from the inside out, with the innermost expression evaluated first. –b. Operator precedence rule: Operators in the same expression are evaluated in the following order: unary +, - first *, /, % next binary +, - last

17 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-17 Arithmetic Expressions -- Expressions with Multiple Operators (Cont’) –c. Associativity rule: Unary operators in the same subexpression and at the same precedence level (such as + and -) are evaluated right to left (right associativity). Binary operators in the same subexpression and at the same precedence level (such as + and -) are evaluated left to right (left associativity).

18 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-18 Arithmetic Expressions -- Expressions with Multiple Operators (Cont’)

19 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-19 Figure 2.8 Evaluation Tree for area = PI * radius * radius;

20 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-20 Figure 2.9 Step-by-Step Expression Evaluation

21 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-21 Arithmetic Expressions -- Expressions with Multiple Operators (Cont’)

22 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-22 Figure 2.10 Evaluation Tree and Evaluation for v = (p2 - p1) / (t2 - t1);

23 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-23 Figure 2.11 Evaluation Tree and Evaluation for z - (a + b / 2) + w * -y

24 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-24 Arithmetic Expressions -- Writing Mathematical Formulas in C

25 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-25 Arithmetic Expressions -- Writing Mathematical Formulas in C (Cont’) The points illustrated in these examples can be summarized as follows: –Always specify multiplication explicitly by using the operator * where needed (formulas 1 and 4). –Use parentheses when required to control the order of operator evaluation (formulas 3 and 4). –Two arithmetic operators can be written in succession if the second is a unary operator (formula 5).

26 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-26 CASE STUDY -- Evaluating a Collection of Coins PROBLEM –Your local bank branch has many customers who save their change and periodically bring it in for deposit. Write a program to interact with the bank’s customers and determine the value of a collection of coins. ANALYSIS –get the count of each type of coin from a customer. –determine the total value of the coins in cents –do an integer division using 100 as the divisor to get the dollar value –remainder of this division will be the leftover change

27 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-27 CASE STUDY -- Evaluating a Collection of Coins (Cont’) DATA REQUIREMENTS –Problem Inputs char first, middle, last /* a customer's initials */ int quarters /* the count of quarters */ int dimes /* the count of dimes */ int nickels /* the count of nickels */ int pennies /* the count of pennies */ –Problem Outputs int dollars /* value in dollars */ int change /* leftover change */ –Additional Program Variables int total_cents /* total value in cents */

28 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-28 CASE STUDY -- Evaluating a Collection of Coins (Cont’) DESIGN –INITIAL ALGORITHM 1.Get and display the customer’s initials. 2.Get the count of each kind of coin. 3.Compute the total value in cents. 4.Find the value in dollars and change. 5.Display the value in dollars and change.

29 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-29 CASE STUDY -- Evaluating a Collection of Coins (Cont’) –REFINEMENT Step 3 Refinement –3.1 Find the equivalent value of each kind of coin in pennies and add these values. Step 4 Refinement –4.1 dollars is the integer quotient of total_cents and 100. –4.2 change is the integer remainder of total_cents and 100.

30 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-30 Figure 2.12 Finding the Value of Coins

31 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-31 Figure 2.12 Finding the Value of Coins (cont’d)

32 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-32 Formatting Numbers in Program Output -- Formatting Values of Type int field width –the number of columns used to display a value E.g. –printf("Results: %3d meters = %4d ft. %2d in.\n", meters, feet, inches); –Results: 21 meters = 68 ft. 11 in.

33 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-33 Formatting Numbers in Program Output -- Formatting Values of Type int (Cont’) Displayed right-justified, preceded by blank spaces –For negative numbers, the minus sign is included in the count of digits displayed. –%2d to display any integer value between -9 and 99 –%4d works for values in the range -999 to 9999 Expands the field width if it is too small for the integer value displayed.

34 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-34 Formatting Numbers in Program Output -- Formatting Values of Type int (Cont’)

35 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-35 Formatting Numbers in Program Output -- Formatting Values of Type double For a type double value, we must indicate both the total field width needed and the number of decimal places desired. –at least one digit before the decimal point %n.mf –n is a number representing the total field width –m is the desired number of decimal places

36 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-36 Formatting Numbers in Program Output -- Formatting Values of Type double (Cont’) E.g. %6.2f –The values displayed are rounded to two decimal places and are displayed right-justified in six columns. It is legal to omit the total field width in the format string placeholder, such as %.mf, which will be printed with no leading blanks.

37 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-37 Formatting Numbers in Program Output -- Formatting Values of Type double (Cont’)

38 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-38 Formatting Numbers in Program Output -- Formatting Values of Type double (Cont’)

39 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-39 Interactive Mode, Batch Mode, and Data Files interactive mode –a mode of program execution in which the user responds to prompts by entering (typing in) data batch mode –a mode of program execution in which the program scans its data from a previously prepared data file

40 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-40 Interactive Mode, Batch Mode, and Data Files (Cont’) Input Redirection –metric <mydata Follow the call to scanf with the echo statement to display the value just stored as a record of the data manipulated by the program. Output Redirection –metric >myoutput Interacting with the running program as above will be difficult because all program output, including any prompting messages, will be sent to the output file. –metric myoutput

41 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-41 Figure 2.13 Batch Version of Miles-to-Kilometers Conversion Program

42 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-42 Interactive Mode, Batch Mode, and Data Files -- Program-Controlled Input and Output Files file pointer –store the information necessary to permit access to a file –FILE*inp, /* pointer to input file */ *outp; /* pointer to output file */ Prepare a file for input or output before permitting access. –inp = fopen("distance.dat", "r"); –outp = fopen("distance.out", "w");

43 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-43 Interactive Mode, Batch Mode, and Data Files -- Program-Controlled Input and Output Files (Cont’) use of the functions fscanf and fprintf –fscanf(inp, "%lf", &miles); –fprintf(outp, "The distance in miles is %.2f.\n", miles); File closing –fclose(inp); –fclose(outp);

44 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-44 Figure 2.14 Miles-to- Kilometers Conversion Program with Named Files

45 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-45 Common Programming Errors Murphy’s Law, “If something can go wrong, it will.” Bugs debugging –removing errors from a program Three kinds of errors –syntax errors –run-time errors –logic errors

46 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-46 Common Programming Errors -- Syntax Errors syntax error –a violation of the C grammar rules, detected during program translation (compilation) A compiler listing is a listing created by the compiler during program translation that shows each line of the source program (preceded by a line number) and any syntax errors detected by the compiler. –E.g. Fig 2.15

47 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-47

48 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-48 Common Programming Errors -- Syntax Errors (Cont’) The line marked for an error is not always the line containing the programmer’s mistake. –Line 274, from line 271 One mistake of the programmer leads to the generation of multiple error messages. –miles

49 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-49 Common Programming Errors -- Syntax Errors (Cont’) Mistyped close-comment character sequence –The compiler is unaware that there is a problem until it comes to the end of the source file without having encountered a } to end the program! –When you begin getting error messages that make you think your compiler isn’t seeing part of your program, recheck your comments carefully. –Mistyping the open-comment sequence /* ? Correct the errors in the declaration part of a program first, then recompile the program before you attempt to fix other errors.

50 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-50 Common Programming Errors -- Run-Time Errors run-time error –an attempt to perform an invalid operation, detected during program execution Dividing a number by zero Fig. 2.16

51 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-51 Figure 2.16 A Program with a Run-Time Error

52 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-52 Common Programming Errors -- Undetected Errors Errors may not prevent a C program from running to completion, but they may simply lead to incorrect results. Input of a mixture of character and numeric data

53 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-53 Figure 2.17 Revised Start of main Function for Coin Evaluation

54 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-54 Common Programming Errors -- Undetected Errors (Cont’) Inputs: –2003 BMC Expected result: Hello BMC, let's check your coins' value in 2003. Actual result: Hello BM, let's check your coins' value in 2003.

55 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-55 Common Programming Errors -- Undetected Errors (Cont’) Further problems –Read on next "scanf(“%lf”, &quarters);" will fail Repair the program –insert a space before the first %c placeholder –scanf(" %c%c%c", &first, &second, &third);

56 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-56 Figure 2.18 A Program That Produces Incorrect Results Due to & Omission

57 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-57 Common Programming Errors -- Logic Errors logic error –an error caused by following an incorrect algorithm Logic errors may not cause run-time errors and do not display error messages. To prevent logic errors, carefully desk check the algorithm and the program.

58 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-58 Chapter Review Every C program has preprocessor directives and a main function. The main function contains variable declarations and executable statements. Variable names must begin with a letter or an underscore (the latter not recommended) and consist of letters, digits, and underscore symbols. A reserved word cannot be used as an identifier.

59 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-59 Chapter Review (Cont’) C’s data types enable the compiler to determine how to store a particular value in memory and what operations can be performed on that value. Three standard data types are int, double, and char. The data type of each variable must be declared. The executable statements are derived from the algorithm and are translated into machine language. Assignment statements are used to perform computations and store results in memory. Function calls are used to get data (functions scanf and fscanf) and to display values stored in memory (functions printf and fprintf).

60 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-60 New Constructs

61 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-61 New Constructs (Cont’)


Download ppt "Chapter 2 Overview of C Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University."

Similar presentations


Ads by Google