Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Type, expression & flow of Control 2011-9-16 胡俊峰.

Similar presentations


Presentation on theme: "Data Type, expression & flow of Control 2011-9-16 胡俊峰."— Presentation transcript:

1 Data Type, expression & flow of Control 2011-9-16 胡俊峰

2 上机通知: 下午 4 点 -6 点, 理科一号楼 2 楼机房上机。 地点:中厅。

3 C 语言的数据类型 C 语言的表达式 关系运算与关系表达式、逻辑运算与逻辑 表达式 C 语言的标准输入输出 条件与分支结构 循环控制

4 C 语言的数据类型 整数、浮点数编码 整数、浮点数运算 字符类型 溢出与精度问题 变量、常量及数组的使用

5 5 Integer Data Types (continued)

6 6 Data types (integer type) Data type size ( bit ) range of values short int 16 -32K ~ 32K-1 (- 32768 ~ 32767) int32-2G ~ 2G-1 Unsigned short1664K -1 ~ 0 unsigned 324G-1 ~ 0

7 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

8

9 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 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 literal  9.234f indicates a float literal  9.234L indicates a long double literal

11 11 Floating –point encoding Floating-point numbers consist of an ``exponent,'' ``significand'', and ``sign bit'' sign bit 1 Exponent 7significand 23

12 Over flow

13 Truncation error

14

15 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

16 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

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

18 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’)

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

20 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 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 22 Declaration Statements (cont.)

23 C 语言的表达式 Statements and expression 算术表达式与算符的优先级 类型转换问题

24 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

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

26 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

27 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

28 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

29 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

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

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

32 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

33 Conversions arithmetic expressions with the same or different data 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 34 Mixed-mode expression (automatic type conversion)

35 关系运算与关系表达式、 逻辑运算与逻辑表达式 关系运算、关系表达式 逻辑运算、逻辑表达式 算术运算的逻辑含义与各种运算的优先级

36 Relational Expressions integer (char) float double Same Type 0 false not 0 true

37 Relational Expressions (cont.) Can accept data which can be arranged in ordering sequence

38 Relational Expressions (cont.) Characters behave the same way as an integer in a relational expression

39 Relational Expressions (cont.) —— evaluate and then compare have lower precedence

40 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

41 Truth table of && (and) R1 && R201 000 101

42 Truth table of || (or) b1 || b201 001 111

43 Logical Operation ! (NOT)

44 Precedence of operators You can always use parenthesis to change the precedence of operators Relational operation logical operation

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

46 Logical expressions —— short-circuit evaluation a || b a && b 2 || a > b 0 && a == b

47 Logic operations 1bit 1bit C1 && C2 || ⊕ 1bit

48 Compound Relational Expressions relational expr logical oper relational expr for example: (a > 12) && (a < 20) for example: (c < 70) || (!valid)

49 year%4==0 year%100!=0 0 1 year%400==0 1 0 0 1 Is leap year: y%4 == 0 && (y%100 != 0 || y%400 == 0) Input a year 1 0 1 0 y%100 != 0  y%100 No zero  true Zero  false

50 C 语言的标准输入输出 标准输入输出原理 输入 \ 输出格式串中的占位符与转义字符 输入输出函数的返回值

51 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

52 printf() arg1arg2 … conversion Contral string: “%d;%f; %c” arg3 5;12.000000;A

53 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 54 Displaying Numerical Values (cont.) printf(“conversion control sequence” , argument list)

55 55 Displaying Numerical Values(cont.) Invoking or calling the printf() function display as an integer Escape sequence

56

57 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

58 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

59 scanf() arg1arg2 … conversion Contral string: “%d;%f; %c” arg3 5 12.000000 A

60 scanf() function

61 条件与分支结构 程序分支与语句块 statement block, compound statement 条件语句的组合与嵌套 Switch 语句与条件表达式

62 Selection selection is a single-entry/single-exit structure: execute only when condition is satisfied. true false Relational expression printf( “Passed”); S >= 60

63 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

64 if (grade >= 60) { printf(“passed”); credit += 2; } false true grade >= 60 printf(“passed”); credit += 2; Compound statement: statements enclosed with brackets.

65 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

66 Exp : #include 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; }

67 The if-else Chain Nested if statement: if (expression1) statement1; else if (expression2) statement2; else statement3;

68

69 The if/else Selection Structure  If student’s grade is greater than or equal to 90 Print “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”

70 if.. else if chain else if if exp1 exp3 exp2 else if 1 1 1 0 case1 case2case3case4

71

72 The switch Statement Terminated with a colon default is optional If the break statement was omitted, the following case would be executed

73 switch (exp) case v1: case v2: statements case v3: case v4: case v5: default:

74 Case study:

75 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

76 Conditional Expression test expression ? value if true : value if false for example: (flag != 0) ? “true” : “false” useful for string output and simple assignment

77 Conditional Expression // show conditional expression ? : string = (flag != 0) ? “true” : “false” ; // same as the following if else if (flag != 0) { string = “true”; } else { string = “false”; }

78 循环控制 循环变量与循环体 循环方式与结束条件 多重循环与算法

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

80 Repetition Statements (cont.)

81 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

82 initializing; testing; altering

83 C Array — 0 based

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

85 while statement (cont.)

86

87 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

88 Enter at least once, often used in verification

89 break and continue statements break statement, used for early termination of a loop continue statement, used for early continuation of a loop

90 break;

91 continue;

92

93 Nested loop #define NUM 4 int i;j; for ( i = NUM; i > 0; i--) { for ( j = 0; j<i; j++) printf(“*”); printf(“\n”); }

94

95

96

97

98

99 第二次作业: 下午 4 点 -6 点, 理科一号楼 2 楼机房上机。 地点:中厅。 上机内容,届时见课程网站。


Download ppt "Data Type, expression & flow of Control 2011-9-16 胡俊峰."

Similar presentations


Ads by Google