program

advertisement
Pengantar C/C++
Outline






C overview
C language elements
Variable declarations and data types
Executable statements
General form of a C program
Arithmetic expressions
2
C overview








C is a high-level programming language
Developed in 1972
By Dennis Ritchie at AT&T Bell Laboratories
From two previous programming languages,
BCPL and B
Used to develop UNIX
Used to write modern operating systems
Hardware independent (portable)
By late 1970s C had evolved to “Traditional
C”
3
C overview (cont.)
 Standardization
 Many slight variations of C existed, and
were incompatible
 Committee formed to create a
“unambiguous, machine-independent”
definition
 Standard created in 1989, updated in
1999
4
C language elements
 Preprocessor
 A system program that modifies a C program
prior to its compilation
 Preprocessor directive
 A C program line beginning with # that provides
an instruction to the preprocessor
 Library
 A collection of useful functions and symbols that
may be accessed by a program
5
C language elements (cont.)
 Constant macro
 A name that is replaced by a particular
constant value before the program is
sent to the compiler
 Comment
 Text beginning with /* and ending with
*/ that provides supplementary
information but is ignored by the
preprocessor and compiler
6
C language elements (cont.)
/*
standard
* Converts distance in miles
to kilometers
header file
*/
#include <stdio.h>
/* printf, scanf definitions comment
*/
#define KMS_PER_MILE 1.609
/* conversion constant */
preprocessor
directive
int main(void)
{
double
constant
kms;
miles,
/* input – distance in miles */
/* output – distance in kilometers */
/* Get the distance in miles */
printf(“Enter the distance in miles> ”);
scanf(”%lf”, &miles);
reserved
word
comment
/* Convert the distance to kilometers */
kms = KMS_PER_MILE * miles;
standard
identifier
/* Display the distance in kilometers */
printf(“That equals %f kilometers.\n”, kms);
return (0);
special symbol
}
reserved
word
punctuation
special symbol
7
C language elements (cont.)
 Function main
int main(void)
 Declarations
 A part of a program that tell the compiler the
names of memory cells in a program
 Executable statements
 Program lines that are converted to machine
language instructions and executed by the
computer
 Reserved word
 A word that has special meaning in C
8
C language elements (cont.)
Reserved Word
Meaning
int
integer; indicates that the
main function returns an
integer value
void
indicates that the main
function receives no data
from the operating system
double
indicates that the memory
cells store real numbers
return
returns control from the
main function to the
operating system
9
C language elements (cont.)
 Standard identifier
 A word having special meaning but one
that a programmer may redefine (but
redefinition is not recommended!)
 Example:
 printf
 scanf
10
C language elements (cont.)
Invalid identifier
Reason invalid
1Letter
begin with a number
double
reserved word
int
reserved word
TWO*FOUR
character * not allowed
joe’s
character ‘ not allowed
11
C language elements (cont.)
 User-defined identifiers
1. An identifier must consist only of letters, digits,
and underscores
2. An identifier cannot begin with a digit
3. A C reserved word cannot be used as an
identifier
4. An identifier defined in a C standard library
should not be redefined
 Examples:
letter_1, letter_2, inches, cent,
CENT_PER_INCH, Hello, variable

Only first 31 characters taking into account
12
C language elements (cont.)
per_capita_meat_consumption_in_1980
per_capita_meat_consumption_in_1995
 The two identifiers would be viewed as identical by a
C compiler
Reserved
Words
Standard
Identifiers
User-Defined
Identifiers
int, void,
double,
return
printf,
scanf
KMS_PER_MILE,
main, miles,
kms
 C compiler considers uppercase and lowercase usage
significantly different
13
C language elements (cont.)
 Program style
 “looks good”  is easier to read and understand
 Programmers spend considerably more time on
program maintenance (updating, modifying)
than they do on its original design or coding
 Meaningful name for a user-defined identifier 
easy to understand
 salary  to store a person’s salary THAN s or
bagel
 If more than 2 or more words, the underscore
character (_) will be better 
dollars_per_hour THAN dollarsperhour
14
C language elements (cont.)
 Choose identifiers long enough to convey the
meaning, but not too long
 lbs_per_sq_in THAN
pounds_per_square_inch
 Don’t choose names that are similar to each
other
 Avoid selecting 2 names that are different only
in their use of uppercase and lowercase letters,
such as LARGE and large
 Not to user 2 names that differ only in the
presence or absence of an underscore, such as
xcoord and x_coord
15
Variable declarations
and data types
 Variable
 A name associated with a memory cell whose
value can change
 Variable declarations
 Statements that communicate to the compiler
the names of variables in the program and the
kind of information stored in each variable
 Data types
 A set of values and operations that can be
performed on those values
16
Data type int
 In mathematics, integers are whole
numbers
 The int data type is used to represent
integers in C
 ANSI C specifies the range: -32767 to 32767
 int can be used in arithmetic operations: add,
subtract, multiply, and divide; also in comparing
two integers
 Examples: -10500, 435, +15, 125, 32767
17
Data type double
 It used to represent real numbers
 Examples: 3.14159, 0.0005, 150.0
 double can be used in arithmetic operations: add,
subtract, multiply, and divide; also in comparing them
 Scientific notation can be used for very large or very
small values
 Example: 1.23E5 = 1.23e5 = 1.23  105
 So, in C scientific notation we read the letter e or E
as “times 10 to the power”
 If the exponent is positive it means “move the
decimal point <the value> places to the right”
 If the exponent is negative it means “move the
decimal point <the value> places to the left”
18
Data type double (cont.)
Valid double Constants
Invalid double Constants
3.14159
0.005
12345.0
15.0e-04 (value is 0.0015)
2.345e2 (value is 234.5)
1.15e-3 (value is 0.00115)
12e+5 (value is 1200000.0)
150 (no decimal point)
.12345e (missing exponent)
15e-0.3 (0.3 is invalid exponent)
12.5e.3 (.3 is invalid exponent)
34,500.99 (comma is not allowed)
19
Data type double (cont.)
Valid double Constants
Invalid double Constants
3.14159
0.005
12345.0
15.0e-04 (value is 0.0015)
2.345e2 (value is 234.5)
1.15e-3 (value is 0.00115)
12e+5 (value is 1200000.0)
150 (no decimal point)
.12345e (missing exponent)
15e-0.3 (0.3 is invalid exponent)


12.5e.3 (.3 is invalid exponent)
34,500.99 (comma is not allowed)
Data type double is an abstraction for the real numbers
because it does not include them all
Some real numbers are too large or too small, and some
real numbers cannot be represented precisely because of
the finite size of a memory cell
20
Data type char
 It used to represent an individual
character value - a letter, a digit, or a
special symbol
 Each type char value is enclosed in
apostrophes (single quotes)
 Examples: ‘A’ ‘z’ ‘2’ ‘9’ ‘*’ ‘:’ ‘”’ ‘ ‘
 You can store a character in a type char
variable and compare character data.
 C allows you to perform arithmetic
operations on type char data, but is has to
be care
21
Executable statements
 Programs in memory
memory
machine language
miles-to-kms
conversion program
miles
memory
machine language
miles-to-kms
conversion program
miles
?
10.00
kms
kms
Before execution
?
of a Program
After execution
16.09
of a Program
22
Assignment statements
 Instruction that stores a value or a
computational result in a variable
 Example: kms = KMS_PER_MILE * miles;
 In C the symbol = is the assignment
operator. Read is as “becomes,” “gets,”
or “takes the value of” rather than
“equals” because it is not equivalent
to the “equal sign” of mathematics.
23
Assignment statements (cont.)
kms = KMS_PER_MILE * miles;
Before
assignment
KMS_PER_MILE
miles
kms
1.609
10.00
?
KMS_PER_MILE
miles
kms
1.609
10.00
16.090
*
After
assignment
24
Assignment statements (cont.)
sum = sum + item;
Before
assignment
sum
item
100
10
+
After
assignment
sum
110
25
Assignment statements (cont.)
 If x and new_x are type double variables,
the statement
new_x = x;
copies the value of variable x into variable
new_x. The statement
new_x = -x;
instructs the computer to get the value of x,
negate that value, and store the result in
new_x
26
Input/Output
operations and functions
 Input operation
 An instruction that copies data from an input device
into memory
 Output operation
 An instruction that displays information stored in
memory
 The most common I/O functions are supplied as part
of the C standard I/O library
#include <stdio.h>
 Function call
 A C function that performs an input or output
operation
27
The printf function
function
name
function arguments
printf(“That equals %f kilometers.\n”, kms);
 Function argument
format string
print list
 Enclosed in parentheses following the
function name; provides information
needed by the functions
 Format string
 In a call to printf, a string of characters
enclosed in quotes (“), which specifies
the form of the output line
28
The printf function (cont.)
 Print list
 In a call to printf, the variables or expressions
whose values are displayed
 Placeholder
 Symbol beginning with % in format string that
indicates where to display the output value
Placeholder
Variable Type
Function Use
%c
%d
%f
%lf
char
int
double
double
printf/scanf
printf/scanf
printf
scanf
29
The printf function (cont.)
 Newline escape sequence
 The character sequence \n, which is used in a
format string to terminate an output line
 Multiple placeholders
 If the print list of a printf call has several
variables, the format string should contain the
same number of placeholders.
 C matches variables with placeholders in left-toright order
30
The printf function (cont.)
 If letter_1, letter_2, and letter_3 are
type char variables and age is type int,
the printf call
printf(“Hi %c%c%c – your age is %d\n”,
letter_1, letter_2, letter_3, age);
displays a line such as
Hi EBK – your age is 35
31
More about \n
 Cursor
 A moving place marker that indicates the next
position on the screen where information will be
displayed
 Example
printf(“Here is the first line\n”);
printf(“\nand this is the second.\n”);
It produces 2 lines of text with a blank line in between:
Here is the first line
1st new line
and this is the second.
2nd new line
32
More about \n (cont.)
printf(“This sentence appears \non two lines. \n”);
 The character after the \n appear on
a new output line:
This sentence appears
on two lines.
new line
33
Displaying Prompts
 Prompt (Prompting message)
 A message displayed to indicate what
data to enter and in what form
printf(“Enter the distance in miles> ”);
scanf(“%lf”, &miles);
 It displays a prompt for square
meters (a numeric value).
34
The scanf function
scanf(“%lf”, &miles);
 It calls function scanf to copy data into the
variable miles
 It copies the data from the standard input
device, usually is the keyboard  the
computer will attempt to store in miles
whatever data the program user types at
the keyboard
 The format string “%lf” consists of a single
placeholder for number, as an input
35
The scanf function (cont.)
number entered
30.5
miles




30.5
Notice that in a call to scanf, the name of each variable
that is to be given a value is preceded by the & character
the & is the C address-of operator  tells the scanf
function where to find each variable into which it is to store
a new value
If the & were omitted  scanf only know a variable’s
current value, not its location in memory, so scanf would
unable to store a new value in the variable
letters entered
BOB
Example: Scanning data line BOB
letter_1
B
letter_2
O
letter_3
B
36
The return statement
return(0);
 It transfers control from the program
to the operating system
 The value 0 is considered the result of
function main’s execution, and it
indicates that your program executed
without error
37
General form of a C program
preprocessor directives
main function heading
{
declarations
executable statements
}
38
Program style
 Spaces in program
 The consistent and careful use of blank spaces can
improve the style of a program
 A blank space is required between consecutive words
in a program line
 The compiler ignores extra blanks between words and
symbols  insert space to improve the readability
and style of a program
 Leave a blank space after a comma and before and
after operators, e.g., *, /, +, -, =
 Indent the body of the main function and insert blank
lines between sections of the program
 But it’s wrong  / * and * /, also MAX ITEMS
39
Comments in programs
 Programmers make a program easier to understand
by using comments to describe the purpose of the
program, the use of identifiers, and the purpose of
each program step  part of program documentation
 Program documentation
 Information (comments) that enhances the
readability of a program
double miles, /* input – distance in miles */
kms; /* output – distance in kilometers */
We document most variables in this way
40
Program style –
using comment
 Header section
 The programmer’s name
 The date of the current version
 A brief description of what the program does
/*
* Programmer: Ucup
Date completed: Sep 12, 2005
* Instructor: Irfan
Class: CI1301
*
* Calculates and displays the area and circumference
* of a circle
*/
41
Program style –
using comment (cont.)


Before you implement each step in the initial algorithm, you
should write a comment that summarizes the purpose of
the algorithm step
This comment should describe what the step does rather
than simply restate the step in English
/* Convert the distance to kilometers. */
kms = KMS_PER_MILE * miles;
is more descriptive and hence preferable to
/* Multiply KMS_PER_MILE by miles and store result in kms. */
kms = KMS_PER_MILE * miles;
42
Arithmetic expressions
Arithmeti
c
Operator
+
*
/
%
Meaning
Examples
addition
2
+
2
–
2
*
/
2
2
5 +
5.0
subtraction
5 –
5.0
multiplication 5 *
5.0
division
5.0
5 /
remainder
5 %
is 7
2.0 is
is 3
2.0 is
is 10
2.0 is
2.0 is
is 2
is 1
7.0
3.0
10.0
2.5
43
Arithmetic expressions (cont.)
 Result of integer division
3 / 15
15 / 3
16 / 3
17 / 3
2
=
=
=
=
0
5
5
5
18 / 3 = 6
16 / - 3 varies
0/4=0
4 / 0 is undefined
7/2
299 / 100
3
2
7
100
6
1
299
200
7%2
99
299 % 100
44
Arithmetic expressions (cont.)
 Result of % operation
3
4
5
6
7
8
%
%
%
%
%
%
5
5
5
5
5
5
=
=
=
=
=
=
3
4
0
1
2
3
5%3=2
5%4=1
15 % 5 = 0
15 % 6 = 3
15 % -7 varies
15 % 0 is undefined
45
Arithmetic expressions (cont.)
 The formula
m equals (m / n) * n + (m % n)
 Examples:
7
equals (7 / 2) * 2 + (7 % 2)
equals 3
*2+
1
299 equals (299 / 100) * 100 + (299 % 100)
equals
2
* 100 +
99
46
Data type of an expression
ace + bandage
 is type int if both ace and bandage are
type int; otherwise, it’s type double
 It’s as an example of the general form
ace arithmetic_operator bandage
 Mixed-type expression
 An expression with operands of different types
 The data type of such a mixed-type expression
will be double
47
Mixed-type assignment
statement
 Mixed-type assignment
 The expression being evaluated and the variable
to which it is assigned have different data types
 Example:
m = 3;
n = 2;
p = 2.0;
x = m / p;
m
n
p
x
y
y = m / n;
x = 9  0.5;
n = 9  0.5;
3
2
x
n
4.5
4
2.0
1.5
1.0
48
Expressions with
multiple operators
 Unary operator
 An operator with one operand
 Examples:
 negation () and plus () operators
 x =  y; p =  x  y;
 Binary operator
 An operator with two operands
 When  and  are used to represent addition
and subtraction, they are binary operators
 x = y  z; z = y  x;
49
Rules for
evaluating expressions

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.
Operator precedence rule

Operators in the same expression are evaluated in the
following order




Unary , 
, , %
Binary , 
Association rule

first
next
last
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).
50
Rules for
evaluating expressions (cont.)
x  y  z  a  b  c  d
can be written in a more readable form using parentheses:
(x  y  z)  (a  b)  (c  d)

The formula for the area of a circle
a = r2
can be written in C as
area = PI  radius  radius;
where the constant macro PI = 3.14159
area = PI * radius * radius
1
*
c
2
*
area
area
=
PI
*
3.14159
radius
*
radius
2.0
2.0
6.28318
12.56636
51
Rules for
evaluating expressions (cont.)
z  (a  b  2)  w  -y
containing type int only.
z - (a + b / 2) + w * -y
1 / a,b
3 - a
z
a
b
w
y
8
3
9
2
-5
+ w
* -y
2
-5
z 2 + a
5 -
4 * b
8
(a
+
3
b
/
2)
9
c
4
6 +
z
5
7
10
1
11
52
Writing mathematical
formulas in C
Mathematical
Formula
1.
2.
b * b – 4 * a * c
a + b – c
3.
ab
cd
(a + b) / (c + d)
4.
1
1 x2
1 / (1 + x * x)
5.



b2 – 4ac
a + b – c
C Expression
a  –(b + c)
a * –(b + c)
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)
53
Case study: evaluating a
collection of coins


It demonstrates the manipulation of type int data (using /
and %) and type char data
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 their customers and determine the value of a
collection of coins.
Analysis

To solve this problem, you need to get the count of each type
of coin (quarters, dimes, nickels, pennies) from a customer.
From those counts, you can determine the total value of the
coins in cents. Once you have that figure, you can do an
integer division using 100 as the divisor to get the dollar value;
the remainder of this division will be the leftover change. In
the data requirements, list the total value in cents
(total_cents) as a program variable, because it is needed as
part of the computation process but is not a required problem
output. To personalize the interaction, get each customer’s
initials before getting the coin counts.
54
Case study: evaluating a
collection of coins (cont.)

Data requirements

Problem inputs
char first, middle, last /* a customer’s
int quarters
/* the count of
int dimes
/* the count of
int nickels
/* the count of
int pennies
/* the count of

*/
*/
*/
*/
*/
Problem outputs
int dollars
int change

initials
quarters
dimes
nickels
pennies
/* value in dollars
/* leftover change
*/
*/
Additional program variables
int total_cents
/* total value in cents
*/
55
Case study: evaluating a
collection of coins (cont.)

Design
 Initial algorithm
1.
2.
3.
4.
5.
Get and display the customer;s 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
 Step 3 and 4 may need refinement. Their refinement are:
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 in the integer quotient of total_cents and 100
4.2 change is the integer remainder of total_cents and 100

Implementation
 The program is shown in the following
56
Case study: evaluating a
collection of coins (cont.)
/*
* Determines the value of a collection of coins
*/
#include <stdio.h>
int main(void) {
char first, middle, last; /* input – 3 initials
*/
int pennies, nickels;
/* input – count of each coin type */
int dimes, quarters;
/* input – count of each coin type */
int change;
/* output – change amount
int dollars;
/* output – dollar amount
int total_cents;
/* total cents
*/
*/
*/
/* Get and display the customer’s initials */
printf(“Type in 3 initials and press return> ”);
scanf(“%c%c%c”, &first, &middle, &last);
printf(“Hello %c%c%c, let’s see what your coins are worth.\n”,
first, middle, last);
57
Case study: evaluating a
collection of coins (cont.)
/* Get the count of each kind of coin */
printf(“Number of quarters> ”);
scanf(“%d”, &quarters);
printf(“Number of dimes
> ”);
scanf(“%d”, &dimes);
printf(“Number of nickels > ”);
scanf(“%d”, &nickles);
printf(“Number of pennies > ”);
scanf(“%d”, &pennies);
/* Compute the total value in cents */
total_cents = 25 * quarters + 10 * dimes + 5 nickles + pennies;
/* Find the value in dollars and change */
dollars = total_cents / 100;
change = total_cents % 100;
/* Display the value in dollars and change */
printf(“\nYour coins are worth %d dollars and %d cents.\n”,
dollars, change);
return(0);
}
58
Case study: evaluating a
collection of coins (cont.)
Type in 3 initials and press return> BMC
Hello BMC, let’s see what your coins are worth.
Number of quarters> 8
Number of dimes
> 20
Number of nickels > 30
Number of pennies > 77
Your coins are worth 6 dollars and 27 cents.
59
Formatting value of type int
 Simply add a number between the % and the d of the
%d placeholder in the printf format string
 Field width
 The number of columns used to display a value
Value
234
234
234
234
Format
%4d
%5d
%6d
%1d
Displayed
Output
234
234
234
234
Value
-234
-234
-234
-234
Format
%4d
%5d
%6d
%1d
Displayed
Output
-234
-234
-234
-234
60
Formatting value of type
double
 It must indicate both the total field width needed and
the number of decimal places desired
 The form of the format string placeholder is %n.mf
where n is a number representing the total field width,
and m is the desired number of decimal places
 Displaying x using format string placeholder %6.2f
Value of
x
-99.42
.123
-9.536
Displayed
Output
-99.42
0.12
-9.54
Value of x
-25.554
99.999
999.4
Displayed
Output
-25.55
100.0
999.40
61
Formatting value of type
double (cont.)
Value
3.14159
3.14159
3.14159
.1234
-.006
-.006
Forma
t
%5.2f
%3.2f
%5.3f
%4.2f
%8.3f
%.3f
Displayed
Output
3.14
3.14
3.142
0.12
-0.006
-0.006
Value
3.14159
3.14159
3.14159
-.006
-.006
-3.14159
Format
%4.2f
%5.1f
%8.5f
%4.2f
%8.5f
%.4f
Displayed
Output
3.14
3.1
3.14159
-0.01
-0.00600
-3.1416
62
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
 E.g. our previous program
 Batch mode
 A mode of program execution in which the program
scans its data from a previously prepared data file
 Input redirection
 E.g. In the UNIX and MS-DOS OS, program take its
input from file mydata instead of from the keyboard by
placing the symbols <mydata at command prompt

metric <mydata
63
Batch version program
/*
* Converts distance in miles to kilometers
*/
#include <stdio.h>
/* printf, scanf definitions */
#define KMS_PER_MILE 1.609
/* conversion constant */
int main(void)
{
double
kms;
miles,
/* input – distance in miles */
/* output – distance in kilometers */
/* Get and echo the distance in miles */
scanf(”%lf”, &miles);
printf(“The distance in miles is %.2f.\n”, miles);
/* Convert the distance to kilometers */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers */
printf(“That equals %.2f kilometers.\n”, kms);
return (0);
}
The distance in miles is 112.00.
That equals 180.21 kilometers.
64
Echo prints vs Prompts
scanf(“%lf”, &miles);

It gets a value for miles from the first (and only) line of the
data file. Because the program input comes from a data file,
there’s no need to precede with a prompting message.
Instead we use
printf(“The distance in miles is %.2f.\n”, miles);

This statement echo prints or displays the value just stored
in miles and provides a record of the data manipulated by
the program
Output redirection


Redirect program output to a disk file instead of to the screen
E.g. In the UNIX and MS-DOS OS, program put its output to
file myoutput by placing the symbols >myoutput at command
prompt


metric >myoutput
For input and output file, it will be better to use the command
line

metric <mydata >myoutput
65
Program with Named Files
/*
* Converts distance in miles to kilometers
*/
#include <stdio.h> /* printf, scanf, fprint, fscanf, fopen, fclose definitions */
#define KMS_PER_MILE 1.609 /* conversion constant */
int main(void)
{
double miles, /* input – distance in miles
*/
kms; /* output – distance in kilometers */
FILE *inp,
/* pointer to input file
*/
*outp;
/* pointer to output file
*/
/* Open the input and output files */
inp = fopen(”c:distance.dat”, “r”);
outp = fopen(“c:distance.out”, “w”);
/* Get and echo the distance in miles */
fscanf(inp, ”%lf”, &miles);
fprintf(outp, “The distance in miles is %.2f.\n”, miles);
/* Convert the distance to kilometers */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers */
fprintf(outp, “That equals %.2f kilometers.\n”, kms);
/* Close files */
fclose(inp);
fclose(outp);
return (0);
}
Contents of input file distance.dat
112.00
Contents of output file distance.out
The distance in miles is 112.00.
That equals 180.21 kilometers.
66
Common programming errors
 Murphy’s Law: “If something can go
wrong, it will”
 Debugging – correcting error from a
program
 According to computer folklore,
computer pioneer Dr. Grace Murray
Hopper diagnosed the first hardware
error caused by a large insect found
inside a computer component)
67
Syntax errors
 The violation of the C grammar rules,
detected during program translation
(compilation)
 Examples:
 Missing semicolon at the end of the variable
declaration (in line 271)
 Undeclared variable miles (detected in lines 275
& 278)
 Last comment is not closed because of blank in
* / close-comment sequence (in line 280)
68
Syntax errors (cont.)
221 /* Converts distance in miles to kilometers */
222
223 #include <stdio.h>
/* printf, scanf definitions */
266 #define KMS_PER_MILE 1.609 /* conversion constant */
267
268 int
269 main(void)
270 {
271
double kms
272
273
/* Get the distance in miles */
274
printf(“Enter the distance in miles> ”);
***** Semicolon added at the end of the previous source line
275 scanf(“%lf”, &miles);
***** Identifier “miles” is not declared within this scope
***** Invalid operand of address-of operator
276
277
/* Convert the distance to kilometers */
278
kms = KMS_PER_MILE * miles;
***** Identifier “miles” is not declared within this scope
279
280
/* Display the distance in kilometers * /
281
printf(“That equals %f kilometers.\n”, kms);
282
283
return (0);
284 }
***** Unexpected end-of-file encountered in a comment
***** “}” inserted before end-of-file
69
Run-Time errors
 An attempt to perform an invalid operation,
detected during program execution
 Occurs when the program directs the
computer to perform an illegal operation,
such as dividing a number by zero
 If it occur the computer will stop executing
your program and will display a diagnostic
message that indicates the line where there
error was detected
70
Run-Time errors (cont.)
111
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#include <stdio.h>
int
main(void)
{
int first, second;
double temp, ans;
printf(“Enter two integers> ”);
scanf(“%d%d”, &first, &second);
temp = second / first;
ans = first / temp;
printf(“The result is %.3f\n”, ans);
return (0);
}
Enter two integers? 14 3
Arithmetic fault, divide by zero at line 272 of routine main
71
Undetected errors
 It leads to incorrect result
 It has to predict the results your program should
produce and verify that the actual output is correct
 A very common source of incorrect results in C
programs is the input of a mixture of character and
numeric data
 scanf’s different of the %c placeholder on the one
hand, and of the %d and %lf to the other
 scanf first skips any blanks and carriage returns in
the input when a numeric value is scanned, but,
scanf skips nothing when it scans a character unless
the %c placeholder preceded by a blank
72
Undetected errors (cont.)

Revised start of main function for Coin Evaluation
int main(void) {
char first, middle, last;
int pennies, nickels;
int dimes, quarters;
int change;
int dollars;
int total_cents;
int year;
/*
/*
/*
/*
/*
/*
/*
input – 3 initials
*/
input – count of each coin type */
input – count of each coin type */
output – change amount
*/
output – dollar amount
*/
total cents
*/
current year
*/
/* Get the current year */
printf(“Enter the current year and press return> ”);
scanf(“%d”, &year);
/* Get the program user’s initials */
printf(“Type in 3 initials and press return> ”);
scanf(“%c%c%c”, &first, &middle, &last);
printf(“Hello %c%c%c, let’s check your coins’ value in %d.\n”,
first, middle, last, year);
73
Undetected errors (cont.)
 If the user types in 2005 and then the
letters BMC, we would expect the
second call to printf to display:
Hello BMC, let’s check your coins’ value in 2005.
 Instead, it displays the message:
Hello
BM, let’s check your coins’ value in 2005.
74
Undetected errors (cont.)

Why? Let’s see the status of memory
year


first
second
third
The value of year is correct, but the three characters stored
are not ‘B’, ‘M’, “C’, but ‘\n’, ‘B’, and ‘M’. The ‘\n’ in first is the
character that results from the user pressing the <return>
key after entering the number 2005
The scan of 2005 stopped at this character, so it was the
first character processed by the statement
2005
\n
B
M
scanf(“%c%c%c”, &first, &middle, &last);


Because the letter C was not yet scanned, it will be scanned
during the next scanf call. This will lead to further
problems.
By the following code, scanf will skip spaces (including
carriage returns) before scanning a character
scanf(“ %c%c%c”, &first, &middle, &last);
75
Logic errors
 An error caused by following an incorrect algorithm
 Usually logic error do not cause run-time errors and
do not display error messages  difficult to detect!
 The only sign of a logic error may be incorrect
program output
 You can detect it by testing the program thoroughly,
comparing its output to calculated results
 You can prevent it by carefully desk checking the
algorithm and the program before you type it in
 Debugging can be time consuming  plan your
program solutions carefully and desk check them to
eliminate bugs early
76
Logic errors on a program
#include <stdio.h>
int main(void) {
int first, second, sum;
printf(“Enter two integers> ”);
scanf(“%d%d”, first, second); /* ERROR! Should be &first, &second */
sum = first + second;
printf(“%d + %d = %d\n”, first, second, sum);
return (0);
}
Enter two integers> 14 3
5971289 + 5971297 = 11942586
77
Download