data type, expression & flow of control 2011-9-16 胡俊峰
TRANSCRIPT
Data Type, expression & flow of Control
2011-9-16 胡俊峰
上机通知: 下午 4 点 -6 点,
理科一号楼 2 楼机房上机。 地点:中厅。
C 语言的数据类型 C 语言的表达式 关系运算与关系表达式、逻辑运算与逻辑
表达式 C 语言的标准输入输出 条件与分支结构 循环控制
C 语言的数据类型 整数、浮点数编码 整数、浮点数运算 字符类型 溢出与精度问题 变量、常量及数组的使用
5
Integer Data Types (continued)
6
Data types (integer type)
Data typesize
( bit ) range of values
short int 16-32K ~ 32K-1(- 32768 ~ 32767)
int 32 -2G ~ 2G-1
Unsigned short 16 64K -1 ~ 0
unsigned 32 4G-1 ~ 0
Character Data Type
ASCII character set (A-Za-z0-9, etc.)
stored in binary number format
uses char keyword
char is a single byte in size
also used for small integers
Floating Point Data Types
real numbers with a decimal and/or exponent (1.5 or 2.67e-3)
stored in floating point format (mantissa, exponent and sign bit)
single precision uses float keyword double precision uses double keyword long modifier can be applied to double
10
Floating-Point Data Types (cont.)
float literal is indicated by appending an f or F long double is created by appending an l or L
9.234 indicates a double literal9.234f indicates a float literal9.234L indicates a long double literal
11
Floating –point encoding Floating-point numbers consist of an ``exp
onent,'' ``significand'', and ``sign bit''
sign bit 1 sign bit 1 Exponent 7 significand 23
Over flow
Truncation error
C Constants
representation of a number, character or group of characters (i.e. a string)
a constant has a value and a type
integer, floating point, character, string
Integer Constants
hexadecimal, starts with 0x, digits are 0 – 9, a - f (e.g. 0x5e, 0xFF, 0X1234)
octal, starts with 0, digits are 0 - 7 (e.g. 017)
decimal, digits are 0 – 9 (e.g. 200, 7, 32767)
can have u (unsigned) or l (long) modifier suffix
Floating Point Constants
use decimal and/or exponential notation, digits are 0 – 9 with e and + or - (e.g. 1.5, 6.22e-2, 3e1, 2e+9)
single precision, uses f suffix (e.g. 1.5f)
double precision, default case (e.g. 1.5)
long double, uses L suffix (e.g. 1.5L)
Character Constants
enclosed in single quotes (e.g. ‘a’)
ASCII encoding
alphanumerics (e.g. ‘A’, ‘7’) and special characters (e.g. ‘$’, ‘%’)
escape sequences (e.g. ‘\n’, ‘\r’, ‘\\’) or in octal notation (e.g. ‘\377’, ‘\0’)
String Constants
contiguous group of characters
enclosed in double quotes (e.g. “how did I get here?”)
null terminated (‘\0’ char is at the end)
Variables
have a name, type and value
type name; (e.g. int sum;)
type name = initial_value; (e.g. int sum = 0;)
type name1, name2; (e.g. int sum1, sum2;)
21
data type variableName1 [, variableName2];
int i, j = 90; short si; char c1 = 'a'; float balance, profit, loss;
Variable declaration :
Const of char
Const of integer
initialization
22
Declaration Statements (cont.)
C 语言的表达式 Statements and expression 算术表达式与算符的优先级 类型转换问题
C Expressions
constants, variables, functions calls and combinations of these (almost everything!)
evaluate to a type and value
examples: x, x + y, (x + y * z), sum = x + y
C Statements an expression followed by a semicolon ( ; )
{ } – compound statement or block; the only statement not requiring a terminating ;
( ) required around control expression of a conditional or iterative statement (e.g. if statement)
C Operators
assignment (=) and arithmetic operators (+ - * / %)
precedence, which operation is done first
associatively, how operations group when there is equal precedence
use parentheses ( ) for more control of the grouping
Assignment Operator
assignment = (a = 2)
the value of the “object” on the left side is replaced by the value of the expression on the right side
an “object” is a manipulatable region of storage (i.e. you are allowed to update its value)
the left side must be an “lvalue”, an expression which evaluates to an object (e.g. a variable)
has low precedence and associates right-to-left
Arithmetic Operators : Binary
addition + (a + b)
subtraction - (a - b)
multiplication * (a * b)
division / (a / b)
modulus % (a % b)
* / % have higher precedence than + - and all associate left-to-right
Arithmetic Operators : Unary
plus + (+ a) equivalent to (0 + a)
minus - (- a) equivalent to (0 – a)
higher precedence than binary arithmetic operators
associate right-to-left
Precedence of Operators
defines which operators take effect first
consult the operator precedence table
a * b + c is equivalent to (a * b) + c instead of a * (b + c)
Associativity of Operators
defines how operations group when the operators have equal precedence
consult the operator precedence table
a - b + c is equivalent to (a - b) + c instead of a - (b + c)
Grouping Parentheses
can use parentheses ( ) to force the order of evaluation
a * (b + c) instead of a * b + c
a – (b + c) instead of a – b + c
Conversions arithmetic expressions with the same or different dat
a type operands
if the same data type, the operations will be performed in that type
if different data types, the smaller type is usually converted to the bigger type before the operations are performed
f1 = 2 / 100 vs f1 = 2 / 100.0
34
Mixed-mode expression (automatic type conversion)
关系运算与关系表达式、逻辑运算与逻辑表达式 关系运算、关系表达式 逻辑运算、逻辑表达式 算术运算的逻辑含义与各种运算的优先级
Relational Expressions
integer (char)floatdouble
Same Type
0 falsenot 0 true
Relational Expressions (cont.)
Can accept data which can be arranged in ordering sequence
Relational Expressions (cont.) Characters behave the same way as an integer
in a relational expression
Relational Expressions (cont.) —— evaluate and then compare have lower precedence
Logical Operations
Can take in operands that evaluated as true (1) or false (0)
Use && (and), || (or), ! (not) to build more complex conditional expressions.
Logical expression is another kind of conditional expression and can also be used directly in selection
Truth table of && (and)
R1 && R2 0 1
0 0 0
1 0 1
Truth table of || (or)
b1 || b2 0 1
0 0 1
1 1 1
Logical Operation ! (NOT)
Precedence of operators
You can always use parenthesis to change the precedence of operators
Relational operation
logical operation
Logical expressions —— conditional expressions
Can take in any valid expression as operands
0 is interpreted as False
None 0 is interpreted as True
int i = 15, j = 30;
double a = 12.0, b = 2.0, complete = 0.0;
Logical expressions —— short-circuit evaluation
a || b a && b
2 || a > b 0 && a == b
Logic operations
1bit 1bit
C1 && C2
||
⊕ 1bit
Compound Relational Expressions relational expr logical oper relational expr
for example: (a > 12) && (a < 20)
for example: (c < 70) || (!valid)
year%4==0
year%100!=00
1
year%400==01
0
0
1
Is leap year: y%4 == 0 && (y%100 != 0 || y%400 == 0)
Input a year
10 1
0
y%100 != 0 y%100No zero trueZero false
C 语言的标准输入输出 标准输入输出原理 输入 \ 输出格式串中的占位符与转义字符 输入输出函数的返回值
printf()
formatted output to the console
printf(control string, variable argument list)
the control string can be simple text or can be embedded with conversion specifications (these begin with a % and end with a conversion character)
the variable argument list is a comma separated list of expressions, and each argument must correspond to one conversion specification in the control string
printf()
arg1 arg2 …
conversion Contral string: “%d;%f; %c”
arg3
5;12.000000;A
printf() Examples
printf(“This is simple text for output”)
printf(“My bowling average is %d”, average)
printf(“The date is %i %i %i”, 2, 5, 2003)
printf(“The answer is %f”, somefloatvalue)
54
Displaying Numerical Values (cont.)
printf(“conversion control sequence” , argument list)
55
Displaying Numerical Values(cont.)
Invoking or calling the printf() functiondisplay as an integer
Escape sequence
printf() Conversion Characters
d or i – integer in decimal
o – integer in octal
x – integer in hexadecimal
e, f, g – floating point
c – single character
s – character string
The scanf() function formatted input from the console
scanf(control string, variable argument address list)
the control string can be simple text or can be embedded with conversion specifications (these begin with a % and end with a conversion character)
the variable argument list is a comma separated list of argument address, and each argument address must correspond to one conversion specification in the control string
scanf()
arg1 arg2 …
conversion Contral string: “%d;%f; %c”
arg3
5 12.000000 A
scanf() function
条件与分支结构 程序分支与语句块 statement block, compound statement 条件语句的组合与嵌套 Switch 语句与条件表达式
Selection
selection is a single-entry/single-exit structure: execute only when condition is satisfied.
true
falseRelationa
lexpressio
n
printf( “Passed”);
S >= 60
if statement
single selection
uses the if keyword
controlled by a test expression, typically a relational expression, which must be enclosed in parentheses ( )
select a single statement or a compound statement (i.e. a block)
the statement is selected if the test expression is true
if (grade >= 60){ printf(“passed”); credit += 2; }
false
true
grade >= 60
printf(“passed”); credit += 2;
Compound statement: statements enclosed with brackets.
The if-else Statement
if (expression)
statement1;
else
statement2; If the value of expression is 0 the statement
after the reserved word else, statement2, is executed
Exp : #include <stdio.h>
int main (){ int score; printf("Please input your score:"); scanf("%d",&score); if (score>=60){ printf("Passed!\n"); } else
printf("Sorry you failed!\n"); return 0;}
The if-else Chain Nested if statement:
if (expression1) statement1;else if (expression2) statement2; else statement3;
The if/else Selection Structure
If student’s grade is greater than or equal to 90Print “A”
else If student’s grade is greater than or equal to 80 Print “B”else If student’s grade is greater than or equal to
70 Print “C” else If student’s grade is greater than or equal
to 60 Print “D” else Print “F”
if .. else if chain else if
if
exp1
exp3
exp2else if 1
1
1
0
case1 case2 case3 case4
The switch Statement
Terminated with a colon
default is optional
If the break statement was omitted, the following case would be executed
switch (exp)
case v1:
case v2:
statements
statements
statements
statements
statements
case v3:
case v4:
case v5:
default:
Case study:
Conditional Operator ? : (a ? b : c)
has three operands
use as shorthand for a simple if else
conditional operator has low precedence and associates right-to-left
Conditional Expression
test expression ? value if true : value if false
for example: (flag != 0) ? “true” : “false”
useful for string output and simple assignment
Conditional Expression// show conditional expression ? :
string = (flag != 0) ? “true” : “false” ;
// same as the following if else
if (flag != 0){ string = “true”;}else{ string = “false”;}
循环控制 循环变量与循环体 循环方式与结束条件 多重循环与算法
Repetition Statements
repeat statement(s) a controlled number of times; can be infinite
controlled by a test expression, typically a relational expression, which must be enclosed in parentheses ( )
control a single statement or a compound statement (i.e. a block)
Repetition Statements (cont.)
for statement
good for counter-controlled or indexed loops
uses for keyword
index variable or loop counter (typically an integer variable), controls the loop
condition is tested at the top of the loop (i.e. before executing the loop statements)
has initialization and update expressions for manipulating the loop counter
initializing;
testing;
altering
C Array — 0 based
while statement
good for flag or sentinel value conditions
uses while keyword
condition is tested at the top of the loop (i.e. before executing the loop statements)
while statement (cont.)
do while statement
good for flag or sentinel value conditions, when you need to execute the loop statements at least once
uses do and while keywords (as a pair)
condition is tested at the bottom of the loop (i.e. after executing the loop statements)
requires a semicolon ; at the end
Enter at least once, often used in verification
break and continue statements
break statement, used for early termination of a loop
continue statement, used for early continuation of a loop
break;
continue;
Nested loop
#define NUM 4 int i;j; for ( i = NUM; i > 0; i--) { for ( j = 0; j<i; j++) printf(“*”); printf(“\n”); }
第二次作业:
下午 4 点 -6 点, 理科一号楼 2 楼机房上机。 地点:中厅。 上机内容,届时见课程网站。