midterm exam review
TRANSCRIPT
Midterm ExamReview
Program Design (I)2021 Fall
Fu-Yin CherngDept. CSIE, National Chung Cheng University
Please Notice
● This is just a quick review of the previous lesson● This doesn’t mean that the questions of the midterm exam will be only from
the contents of these slides● The purpose of these slides is to let you know where are the important parts
in each chapter which related to the midterm exam
Ch 2. C Fundamentals
Variables and Types
● The locations to store data are called Variable ● Every variable must have a type, which specifics what kind of data it will store● Wide variety of types, e.g., int and float.
4
data
variable
int: 1, 2, 10, 1000
float: 0.1, 0.01, 10.129
Assignment
● Now, we have declared variable for later use, how to store data in the variables?
● We give a value to a variable by assignment
● Don’t assignemt before declaration● Assign the correct type of data to
the variable○ mixing type might cause some problems
5
int height, length, width, volume;float profit, loss;
height = 8;length = 12;width = 10;profit=2150.48;profit=2150.48f;//a better version
height = 8.1 //mixing type
Printing the Value of a Variable
● printf can be used to display the current value of a variable.● To write the message:
○ where h is the current value of the height variable● We use the following call
6
Height: h
printf("Height: %d\n", height);
%d is a placeholder indicating where the value of height is to be filled in.
Reading Input
● scanf is the C library’s counterpart to printf.● scanf requires a format string to specify the appearance of the input data.
○ f for printf and scanf stands for ”formatted”○ printf and scanf required format string to specify the input/output data (the shape of data)
● The & symbol is usually (but not always) required when using scanf○ hard to explain the meaning of & now, so just remember to add it when using scanf
7
printf("Height: %d Length: %d\n", height, length);
scanf("%d", &i);
tell the printf that that output data is two integar (%d)
reads an integer (%d); stores into i users will input data
Ch 3. Formatted I/O
The pintf Function
● A conversion specification is a placeholder representing a value to be filled in during printing.
○ %d is used for int values○ %f is used for float values
● The information after % character specifies how the value is converted to printed form
9
int x = 1;
printf("%d", x);
//%d specifies that printf is to convert an int value to a string of decimal digits
Conversion Specifications
● A conversion specification can have the form ● m and p are integer constants and X is a letter.
10
%m.pX or %-m.pX
Conversion Specifications
● Both m and p are optional; ● if p is omitted, the period (.) that separates m and p is also dropped.
11
%mX or %-mX
%m.pX or %-m.pX
Conversion Specifications
● For example● Can you identify where is the X, m, and p for each case?
12
%10.2f
%10f
%.2f
Conversion Specifications
● For example● Can you identify where is the X, m, and p for each case?
13
%10.2f: m is 10, p is 2, and X is f.
%10f: m is 10 and p (along with the period) is missing, X is f
%.2f: p is 2 and m is missing, X is f.
Conversion Specifications - minimum field width
● m: minimum field width● specifies the minimum number of characters to print.● If the value to be printed requires fewer than m characters, it’s right-justified
○ Putting a minus sign in front of m causes left justification.● If the value to be printed requires more than m characters, the field width
automatically expands to the necessary size.
14
int i=123;
printf("%4d", i); //output: •123 (• represents the space character.)
printf("%-4d", i); //output: 123•
printf("%2d", i); //output: 123 (auto expand)
Conversion Specifications - precision
● p: precision● the meaning of p depends on the choice of X, the conversion specifier.● For d specifier (display an integer in decimal form)
○ p indicates the minimum number of digits to display (extra zeros are added to the beginning of the number if necessary).
○ If p is omitted, it is assumed to be 1 (%d = %.1d)
15
Conversion Specifications - precision
● For f specifier (display floating-point numbers)○ p indicates how many digits should appear after the decimal point (default is 6). ○ If p is 0, no decimal point is displayed.
16
Conversion Specifications - precision
● e specifier○ Display a floating-point number in expenetial formate (scientific notation)
● For e specifier○ p indicates how many digits should appear after the decimal point (default is 6). ○ If p is 0, no decimal point is displayed○ same as the meaning of p for f specifier
17
Ch 4 Expression
Summary
● Operators○ arithmetic, assignment, relational, logial, and many others (in later chapters)
● Arithmetic Operators○ Operator Precedence and Associativity
● Assignment Operators○ Simple and Compound assignment
19
Expression Evaluation
20
Precedence Name Symbol Associativity
1 (high) increment (postfix) variable++ left
decrement (postfix) variable--
2 increment (prefix) ++variable right
decrement (prefix) --variable
unary plus +variable
unary minus -variable
3 multiplicative * / % left
4 additive + - left
5 (low) (compound) assignment = *= /= %= += -= right
Ch 5. Selection Statements
Relational Operators
● These operators produce 0 (false) or 1 (true) when used in expressions.● The relational operators can be used to compare integers and floating-point
numbers, with operands of mixed types allowed.
int i;
i = 1 < 2.5; // i is 1 (true)
i = 5.6 < 4; // i is 0(false)
Symbol Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
22
Equality Operators
● How about we want to check if i is equal to j?● two equality operators● The equality operators are produce either 0 (false) or 1 (true) as their result.● The equality operators have lower precedence than the relational operators
Symbol Meaning
== equal to
!= not equal to
i < j == j < k;
(i < j) == (j < k);
23
Logical Operators
Symbol Meaning Usage Result
! logical negation (unary) !TRUE!FALSE
FALSETRUE
&& logical and (binary); AND TRUE && TRUEFALSE && TRUEFALSE && FALSE
TRUEFALSEFALSE
|| logical or (binary); OR TRUE | | TRUEFALSE | | TRUEFALSE | | FALSE
TRUETRUEFALSE
24
Logical Operators
● The logical operators also produce 0 (false) or 1 (true) as their result.● The logical operators treat any nonzero operand as a true value and any zero
operand as a false value.
25
Logical Operators
● && and || first evaluate the left operand, then the right one● If the value of the expression can be determined from the left operand alone, the
right operand isn’t evaluated.● (i != 0) is evaluated first. If i isn’t equal to 0, then (j / i > 0) is evaluated.
○ if (j / i > 0) is false, this expression is false● If i is 0, the entire expression must be false, no need to evaluate (j / i > 0)
○ avoid the division by zero
(i != 0) && (j / i > 0)
//if left operand is true, then run right
left operand right operand
26
The else Clause
● An if statement may have an else clause● The statement that follows the word else is executed if the expression has
the value 0 (False).
if (i > j)
max = i;
else
max = j;
if i is less than or equal to j, the value of i > j will be 0 so that the else is executed
if i is larger than j, the value of i > j will be 1 so that the statement inside if is executed
27
Cascaded if Statements
● Although the second if statement is nested inside the first, C programmers don’t usually indent it. Instead, ...
if (n < 0)
printf("n is less than 0\n");
else if (n == 0)
printf("n is equal to 0\n");
else
printf("n is greater than 0\n");
28
Conditional Expressions
● “if expr1 then expr2 else expr3”● The expression is evaluated in stages● expr1 is evaluated first; ● if its value isn’t zero (true), then expr2 is evaluated, and its value (expr2) is
the value of the entire conditional expression.● If the value of expr1 is zero (false), then the value of expr3 is the value of
the conditional expression
29
expr1 ? expr2 : expr3
nonzero (true)
zero (false)
The switch Statement
● The switch statement ● switch statement will test the
value of grade variable ● If match 4, executed the
statements in case 4○ print “Excellent”○ break statement makes the
execution flow jump out of the switch statement
30
switch (grade) {
case 4: printf("Excellent");
break;
case 3: printf("Good");
break;
case 2: printf("Average");
break;
case 1: printf("Poor");
break;
case 0: printf("Failing");
break;
default: printf("Illegal grade");
break;
}
...
if grade == 4
Ch 6. Loops
The while Statement
● The easiest way to set up a loop● below is the general form of the while statement● expression: controlling expression
○ expression to control if the loop will stop or continue● statement: loop body
○ If the expression is true the loop continues to execute
32
while ( expression ) statement
The while Statement
33
i = 1;
while (i < n) /* controlling expression; n will be given by users */i = i * 2; /* loop body */
statement value of i controlling expression action
i = 1; 1 i < n? Yes; continue.
i = i * 2; 2 i < n? Yes; continue.
i = i * 2; 4 i < n? Yes; continue.
i = i * 2; 8 i < n? Yes; continue.
i = i * 2; 16 i < n? No; exit from loop
n = 10
The for Statement
● Example
34
for ( expr1 ; expr2 ; expr3 ) statement
for (i = 10; i > 0; i--)
printf("%d\n", i);
for Statement Idioms
● The for statement is usually the best choice for loops that “count up” (increment a variable) or “count down” (decrement a variable).
● A for statement that counts up or down a total of n times will usually have one of the following forms (idioms)
● Imitating these patterns is helpful to avoid some of the following errors
35
Counting up from 0 to n–1 for (i = 0; i < n; i++)
Counting up from 1 to n for (i = 1; i <= n; i++)
Counting down from n–1 to 0 for (i = n - 1; i >= 0; i--)
Counting down from n to 1 for (i = n; i > 0; i--)
The break Statement
● The break statement can transfer control out of a switch, but it can also be used to jump out of a while, do, or for loop.
● A loop that checks whether a number n is prime can use a break statement to terminate the loop as soon as a divisor is found
● exit from break: n isn’t prime● exit from for: n is prime
36
for (d = 2; d < n; d++){
if (n % d == 0)
break;
}
if (d < n){
printf("%d is divisible by %d\n", n, d);
} else{
printf("%d is prime\n", n);
}
exit the loop when find a divisor is found
The continue Statement
● Example of continue● read a series of numbers and
computes their sum● the loop terminates when 10
nonzero numbers have been read○ so 0 is not counted
● if 0 is read, skipping the rest loop body but remaining inside the loop○ so n will not be increased by 1 if
input is 0
37
n = 0;
sum = 0;
while (n < 10) {
scanf("%d", &i);
if (i == 0){
continue;
}
sum += i;
n++;
/* continue jumps to here */
}
Ch 7. Basic Type
39https://justdocodings.blogspot.com/2018/03/c-data-types.html
long long intlong long int
Character Types
● Today’s most popular character set is ASCII○ American Standard Code for Information Interchange
● a 7-bit code capable of representing 128 (27) characters.● ASCII is often extended to a 256-character code known as Latin-1 that provides the
characters necessary for Western European and many African languages.
40
7-bit code
Operations on Characters
● When a character (char) appears in a computation, C uses its integer value.● Consider the following examples, which assume the ASCII character set:
41
char ch;
int i;
i = 'a'; /* i is now 97 */
ch = 65; /* assign value to char, ch is now 'A' */
ch = ch + 1; /* ch is now 'B' */
ch++; /* ch is now 'C' */
Reading & Writing Using getchar and putchar
● getchar is useful in loops that skip characters as well as loops that search for characters.
● A statement that uses getchar to skip an indefinite number of blank characters:● When the loop terminates, ch will contain the first nonblank character that getchar
encountered.
42
char ch;
while ((ch = getchar()) == ' ');
putchar(ch);
The Usual Arithmetic Conversions
● Two general Strategies of usual arithmetic conversions
43
The type of either operand is a floating type
Neither operand type is a floating type
long double
double
float
unsigned long int
long int
unsigned int
int int
Conversion During Assignment
● Assigning a floating-point number to an integer variable drops the fractional part of the number
● Assigning a value outside the range of the variable’s type to a variable is meaningless
44
int i;
i = 842.97; /* i is now 842 */
i = -842.97; /* i is now -842 */
i = 1.0e20; /*** WRONG ***/
Casting
● Although C’s implicit conversions are convenient, we sometimes need a greater degree of control over type conversion.
● For this reason, C provides casts.● A cast expression has the form
45
( type-name ) expression type-name specifies the type to which the expression should be converted.
Casting
● Cast expressions also let us force the compiler to perform conversions.● To avoid truncation during division, we need to cast one of the operands:● Casting dividend to float causes the compiler to convert divisor to float
also.
46
float quotient;
int dividend = 3, divisor = 2;
quotient = dividend / divisor; // quotient is 1
quotient = (float) dividend / divisor; // quotient is 1.5