You are on page 1of 61

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

Arithmetic Expressions

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-2

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.
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-3

Arithmetic Expressions -- Operators / and % (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-4

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-5

Arithmetic Expressions -- Operators / and % (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-6

Arithmetic Expressions -- Operators / and % (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-7

Arithmetic Expressions -- Operators / and % (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-8

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.


Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-9

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-10

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;

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-11

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;

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-12

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-13

Arithmetic Expressions -- Type Conversion through Casts (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-14

Arithmetic Expressions -- Expressions with Multiple Operators


unary operator
an operator with one operand

binary operator
an operator with two operands

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-15

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-16

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).

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-17

Arithmetic Expressions -- Expressions with Multiple Operators (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-18

Figure 2.8 Evaluation Tree for area = PI * radius * radius;

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-19

Figure 2.9 Step-by-Step Expression Evaluation

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-20

Arithmetic Expressions -- Expressions with Multiple Operators (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-21

Figure 2.10 Evaluation Tree and Evaluation for v = (p2 - p1) / (t2 - t1);

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-22

Figure 2.11 Evaluation Tree and Evaluation for z - (a + b / 2) + w * -y

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-23

Arithmetic Expressions -- Writing Mathematical Formulas in C

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-24

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).
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-25

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 banks 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
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-26

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 */
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-27

CASE STUDY -- Evaluating a Collection of Coins (Cont)


DESIGN
INITIAL ALGORITHM
1. 2. 3. 4. 5. Get and display the customers initials. Get the count of each kind of coin. Compute the total value in cents. Find the value in dollars and change. Display the value in dollars and change.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-28

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-29

Figure 2.12 Finding the Value of Coins

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-30

Figure 2.12 Finding the Value of Coins (contd)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-31

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-32

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.
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-33

Formatting Numbers in Program Output -- Formatting Values of Type int (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-34

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-35

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-36

Formatting Numbers in Program Output -- Formatting Values of Type double (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-37

Formatting Numbers in Program Output -- Formatting Values of Type double (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-38

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-39

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 <mydata >myoutput

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-40

Figure 2.13 Batch Version of Miles-to-Kilometers Conversion Program

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-41

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");
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-42

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);

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-43

Figure 2.14 Miles-toKilometers Conversion Program with Named Files

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-44

Common Programming Errors


Murphys 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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-45

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
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-46

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-47

Common Programming Errors -- Syntax Errors (Cont)


The line marked for an error is not always the line containing the programmers mistake.
Line 274, from line 271

One mistake of the programmer leads to the generation of multiple error messages.
miles

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-48

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 isnt 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.
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-49

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-50

Figure 2.16 A Program with a Run-Time Error

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-51

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

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-52

Figure 2.17 Revised Start of main Function for Coin Evaluation

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-53

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-54

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);

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-55

Figure 2.18 A Program That Produces Incorrect Results Due to & Omission

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-56

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.

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-57

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.
Copyright 2004 Pearson Addison-Wesley. All rights reserved. 2-58

Chapter Review (Cont)


Cs 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).

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-59

New Constructs

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-60

New Constructs (Cont)

Copyright 2004 Pearson Addison-Wesley. All rights reserved.

2-61

You might also like