pengantar c/c++. 2 outline c overview c language elements variable declarations and data types ...
TRANSCRIPT
Pengantar C/C++
2
Outline
C overview C language elements Variable declarations and data types Executable statements General form of a C program Arithmetic expressions
3
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”
4
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
5
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
6
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
7
C language elements (cont.)/** Converts distance in miles to kilometers*/#include <stdio.h> /* printf, scanf definitions */#define KMS_PER_MILE 1.609 /* conversion constant */
int main(void){
double miles, /* input – distance in miles */ kms; /* output – distance in kilometers */
/* Get the distance in miles */printf(“Enter the distance in miles> ”);scanf(”%lf”, &miles);
/* Convert the distance to kilometers */kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers */printf(“That equals %f kilometers.\n”, kms);
return (0);}
preprocessor directive
standard header file comment
constant
reserved word
standard identifier
comment
special symbol
reserved word punctuation
special symbol
8
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 languag
e instructions and executed by the computer Reserved word
A word that has special meaning in C
9
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
10
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
11
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
12
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 digit3. A C reserved word cannot be used as an
identifier4. 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
13
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 co
mpiler
C compiler considers uppercase and lowercase usage significantly different
Reserved Words
Standard Identifiers
User-Defined Identifiers
int, void, double, return
printf, scanf
KMS_PER_MILE, main, miles, kms
14
C language elements (cont.) Program style
“looks good” is easier to read and understand Programmers spend considerably more time on prog
ram 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 bag
el If more than 2 or more words, the underscore charac
ter (_) will be better dollars_per_hour THAN dollarsperhour
15
C language elements (cont.) Choose identifiers long enough to convey the meanin
g, 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 the
ir 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
16
Variable declarationsand 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
17
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, subtr
act, multiply, and divide; also in comparing two integers
Examples: -10500, 435, +15, 125, 32767
18
Data type double It used to represent real numbers Examples: 3.14159, 0.0005, 150.0 double can be used in arithmetic operations: add, subtra
ct, 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”
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)
20
Data type double (cont.)
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
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)
21
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
22
Executable statements Programs in memory
Before execution After execution of a Program of a Program
10.00
16.09
miles
kms
machine languagemiles-to-kms
conversion program
memory
?
?
miles
kms
machine languagemiles-to-kms
conversion program
memory
23
Assignment statements Instruction that stores a value or a comp
utational result in a variable Example: kms = KMS_PER_MILE * miles; In C the symbol = is the assignment oper
ator. Read is as “becomes,” “gets,” or “takes the value of” rather than “equals” because it is not equivalent to the “equal sign” of mathematics.
24
Assignment statements (cont.)kms = KMS_PER_MILE * miles;
Beforeassignment
Afterassignment
KMS_PER_MILE
1.609
miles
10.00 ?
kms
*
KMS_PER_MILE
1.609
miles
10.00 16.090
kms
25
Assignment statements (cont.)sum = sum + item;
Beforeassignment
Afterassignment
sum
100
item
10
+
sum
110
26
Assignment statements (cont.) If x and new_x are type double variables, the st
atementnew_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, nega
te that value, and store the result in new_x
27
Input/Outputoperations 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
28
The printf function
printf(“That equals %f kilometers.\n”, kms);
Function argument Enclosed in parentheses following the functi
on name; provides information needed by the functions
Format string In a call to printf, a string of characters enc
losed in quotes (“), which specifies the form of the output line
function name
function arguments
format string
print list
29
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 w
here to display the output value
Placeholder Variable Type Function Use
%c
%d
%f
%lf
char
int
double
double
printf/scanf
printf/scanf
printf
scanf
30
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-to-right order
31
The printf function (cont.) If letter_1, letter_2, and letter_3 are typ
e 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
32
More about \n Cursor
A moving place marker that indicates the next position on the screen where information will be displayed
Exampleprintf(“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
and this is the second.1st new line
2nd new line
33
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
34
Displaying Prompts
Prompt (Prompting message) A message displayed to indicate what data t
o enter and in what formprintf(“Enter the distance in miles> ”);
scanf(“%lf”, &miles);
It displays a prompt for square meters (a numeric value).
35
The scanf functionscanf(“%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
36
The scanf function (cont.)
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
Example: Scanning data line BOB
miles
30.5
number entered 30.5
letter_1
B
letters entered BOB
letter_2
O
letter_3
B
37
The return statementreturn(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
38
General form of a C program
preprocessor directivesmain function heading{
declarationsexecutable statements
}
39
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
40
Comments in programs Programmers make a program easier to understand by usi
ng 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
41
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 */
42
Program style –using comment (cont.) Before you implement each step in the initial algorithm, you shou
ld 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;
43
Arithmetic expressions
Arithmetic
Operator
Meaning Examples
+
-
*
/
%
addition
subtraction
multiplication
division
remainder
5 + 2 is 7
5.0 + 2.0 is 7.0
5 – 2 is 3
5.0 – 2.0 is 3.0
5 * 2 is 10
5.0 * 2.0 is 10.0
5.0 / 2.0 is 2.5
5 / 2 is 2
5 % 2 is 1
44
Arithmetic expressions (cont.) Result of integer division
3 / 15 = 0 18 / 3 = 615 / 3 = 5 16 / - 3 varies16 / 3 = 5 0 / 4 = 017 / 3 = 5 4 / 0 is undefined
7 / 2
3
72
6
1 7 % 2
299 / 100
2
299100
200
99 299 % 100
45
Arithmetic expressions (cont.) Result of % operation
3 % 5 = 3 5 % 3 = 24 % 5 = 4 5 % 4 = 15 % 5 = 0 15 % 5 = 06 % 5 = 1 15 % 6 = 37 % 5 = 2 15 % -7 varies 8 % 5 = 3 15 % 0 is undefined
46
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
47
Data type of an expression
ace + bandage is type int if both ace and bandage are type in
t; 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
48
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;y = m / n;
x = 9 0.5;n = 9 0.5;
3 2 2.0 1.5 1.0
m n p x y
4.5 4
x n
49
Expressions withmultiple 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;
50
Rules forevaluating 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 ord
er Unary , first , , % next Binary , last
Association rule Unary operators in the same subexpression and at the same precede
nce 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).
51
Rules forevaluating expressions (cont.)
x y z a b c dcan 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 asarea = PI radius radius;
where the constant macro PI = 3.14159
area = PI * radius * radius
*1 c
*
area
2area = PI * radius * radius
3.14159 2.0 2.0
6.28318
12.56636
52
Rules forevaluating expressions (cont.)
z (a b 2) w -ycontaining type int only.
z - (a + b / 2) + w * -y
/1 a,b
+2 a
-3 a
*4 b
-5 c
+6
z
8
z
3
a
9
b
2
w
-5
y
z - (a + b / 2) + w * -y
8 3 9 2 -5
4 5
7 10
1
11
53
Writing mathematicalformulas in 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)
Mathematical Formula
C Expression
1. b2 – 4ac
2. a + b – c
3.
4.
5. a –(b + c)
b * b – 4 * a * c
a + b – c
(a + b) / (c + d)
1 / (1 + x * x)
a * –(b + c)
dc
ba
21
1
x
54
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.
55
Case study: evaluating a collection of coins (cont.) Data requirements
Problem inputschar 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 outputsint dollars /* value in dollars */ int change /* leftover change */
Additional program variablesint total_cents /* total value in cents */
56
Case study: evaluating a collection of coins (cont.) Design
Initial algorithm1. Get and display the customer;s initials2. Get the count of each kind of coin3. Compute the total value in cents4. Find the value in dollars and change5. 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 valuesStep 4 Refinement
4.1 dollars in the integer quotient of total_cents and 1004.2 change is the integer remainder of total_cents and 100
Implementation The program is shown in the following
57
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);
58
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);}
59
Case study: evaluating a collection of coins (cont.)Type in 3 initials and press return> BMCHello BMC, let’s see what your coins are worth.Number of quarters> 8Number of dimes > 20Number of nickels > 30Number of pennies > 77
Your coins are worth 6 dollars and 27 cents.
60
Formatting value of type int Simply add a number between the % and the d of the %d pla
ceholder in the printf format string Field width
The number of columns used to display a value
Value Format Displayed Output
Value Format Displayed Output
234
234
234
234
%4d
%5d
%6d
%1d
234234234234
-234
-234
-234
-234
%4d
%5d
%6d
%1d
-234
-234-234-234
61
Formatting value of type double It must indicate both the total field width needed and the n
umber 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
Displayed Output
Value of x Displayed Output
-99.42
.123
-9.536
-99.42
0.12-9.54
-25.554
99.999
999.4
-25.55
100.0
999.40
62
Formatting value of type double (cont.)
Value Format
Displayed Output
Value Format Displayed Output
3.14159
3.14159
3.14159
.1234
-.006
-.006
%5.2f
%3.2f
%5.3f
%4.2f
%8.3f
%.3f
3.143.14
3.142
0.12
-0.006-0.006
3.14159
3.14159
3.14159
-.006
-.006
-3.14159
%4.2f
%5.1f
%8.5f
%4.2f
%8.5f
%.4f
3.14
3.13.14159-0.01
-0.00600
-3.1416
63
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
64
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 miles, /* input – distance in miles */kms; /* 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.
65
Echo prints vs Promptsscanf(“%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 useprintf(“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 myou
tput 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
66
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.
67
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)
68
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)
69
Syntax errors (cont.)221 /* Converts distance in miles to kilometers */222223 #include <stdio.h> /* printf, scanf definitions */266 #define KMS_PER_MILE 1.609 /* conversion constant */267268 int269 main(void)270 {271 double kms272273 /* 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 operator276277 /* Convert the distance to kilometers */278 kms = KMS_PER_MILE * miles;***** Identifier “miles” is not declared within this scope
279280 /* Display the distance in kilometers * /281 printf(“That equals %f kilometers.\n”, kms);282283 return (0);284 }***** Unexpected end-of-file encountered in a comment***** “}” inserted before end-of-file
70
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
71
Run-Time errors (cont.)111 #include <stdio.h>262263 int264 main(void)265 {266 int first, second; 267 double temp, ans;268269 printf(“Enter two integers> ”);270 scanf(“%d%d”, &first, &second);271 temp = second / first;272 ans = first / temp; 273 printf(“The result is %.3f\n”, ans);274275 return (0);276 }
Enter two integers? 14 3Arithmetic fault, divide by zero at line 272 of routine main
72
Undetected errors It leads to incorrect result It has to predict the results your program should produce a
nd 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 inp
ut when a numeric value is scanned, but, scanf skips nothing when it scans a character unless the %c placeholder preceded by a blank
73
Undetected errors (cont.) Revised start of main function for Coin Evaluation
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 */int year; /* 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);
74
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.
75
Undetected errors (cont.) Why? Let’s see the status of memory
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 statementscanf(“%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 characterscanf(“ %c%c%c”, &first, &middle, &last);
2005
year
\n
first
B
second
M
third
76
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
77
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 35971289 + 5971297 = 11942586