data type, expression & flow of control 2011-9-16 胡俊峰

99
Data Type, expression & flow of Control 2011-9-16 胡胡胡

Upload: francis-gardner

Post on 18-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

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

Data Type, expression & flow of Control

2011-9-16  胡俊峰

Page 2: Data Type, expression & flow of Control 2011-9-16 胡俊峰

上机通知: 下午 4 点 -6 点,

理科一号楼 2 楼机房上机。 地点:中厅。

Page 3: Data Type, expression & flow of Control 2011-9-16 胡俊峰

C 语言的数据类型 C 语言的表达式 关系运算与关系表达式、逻辑运算与逻辑

表达式 C 语言的标准输入输出 条件与分支结构 循环控制

Page 4: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 5: Data Type, expression & flow of Control 2011-9-16 胡俊峰

5

Integer Data Types (continued)

Page 6: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 7: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 8: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 9: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 10: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 11: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 12: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Over flow

Page 13: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Truncation error

Page 14: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 15: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 16: Data Type, expression & flow of Control 2011-9-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

Page 17: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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)

Page 18: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 19: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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)

Page 20: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 21: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 22: Data Type, expression & flow of Control 2011-9-16 胡俊峰

22

Declaration Statements (cont.)

Page 23: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 24: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 25: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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)

Page 26: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 27: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 28: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 29: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 30: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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)

Page 31: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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)

Page 32: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 33: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 34: Data Type, expression & flow of Control 2011-9-16 胡俊峰

34

Mixed-mode expression (automatic type conversion)

Page 35: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 36: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Relational Expressions

integer (char)floatdouble

Same Type

0 falsenot 0 true

Page 37: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Relational Expressions (cont.)

Can accept data which can be arranged in ordering sequence

Page 38: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Relational Expressions (cont.) Characters behave the same way as an integer

in a relational expression

Page 39: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 40: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 41: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Truth table of && (and)

R1 && R2 0 1

0 0 0

1 0 1

Page 42: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Truth table of || (or)

b1 || b2 0 1

0 0 1

1 1 1

Page 43: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Logical Operation ! (NOT)

Page 44: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Precedence of operators

You can always use parenthesis to change the precedence of operators

Relational operation

logical operation

Page 45: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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;

Page 46: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Logical expressions —— short-circuit evaluation

a || b a && b

2 || a > b 0 && a == b

Page 47: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Logic operations

1bit 1bit

C1 && C2

||

⊕ 1bit

Page 48: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Compound Relational Expressions relational expr logical oper relational expr

for example: (a > 12) && (a < 20)

for example: (c < 70) || (!valid)

Page 49: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 50: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 51: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 52: Data Type, expression & flow of Control 2011-9-16 胡俊峰

printf()

arg1 arg2 …

conversion Contral string: “%d;%f; %c”

arg3

5;12.000000;A

Page 53: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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)

Page 54: Data Type, expression & flow of Control 2011-9-16 胡俊峰

54

Displaying Numerical Values (cont.)

printf(“conversion control sequence” , argument list)

Page 55: Data Type, expression & flow of Control 2011-9-16 胡俊峰

55

Displaying Numerical Values(cont.)

Invoking or calling the printf() functiondisplay as an integer

Escape sequence

Page 56: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 57: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 58: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 59: Data Type, expression & flow of Control 2011-9-16 胡俊峰

scanf()

arg1 arg2 …

conversion Contral string: “%d;%f; %c”

arg3

5 12.000000 A

Page 60: Data Type, expression & flow of Control 2011-9-16 胡俊峰

scanf() function

Page 61: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 62: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Selection

selection is a single-entry/single-exit structure: execute only when condition is satisfied.

true

falseRelationa

lexpressio

n

printf( “Passed”);

S >= 60

Page 63: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 64: Data Type, expression & flow of Control 2011-9-16 胡俊峰

if (grade >= 60){ printf(“passed”); credit += 2; }

false

true

grade >= 60

printf(“passed”); credit += 2;

Compound statement: statements enclosed with brackets.

Page 65: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 66: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 67: Data Type, expression & flow of Control 2011-9-16 胡俊峰

The if-else Chain Nested if statement:

if (expression1) statement1;else if (expression2) statement2; else statement3;

Page 68: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 69: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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”

Page 70: Data Type, expression & flow of Control 2011-9-16 胡俊峰

if .. else if chain else if

if

exp1

exp3

exp2else if 1

1

1

0

case1 case2 case3 case4

Page 71: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 72: Data Type, expression & flow of Control 2011-9-16 胡俊峰

The switch Statement

Terminated with a colon

default is optional

If the break statement was omitted, the following case would be executed

Page 73: Data Type, expression & flow of Control 2011-9-16 胡俊峰

switch (exp)

case v1:

case v2:

statements

statements

statements

statements

statements

case v3:

case v4:

case v5:

default:

Page 74: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Case study:

Page 75: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 76: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Conditional Expression

test expression ? value if true : value if false

for example: (flag != 0) ? “true” : “false”

useful for string output and simple assignment

Page 77: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Conditional Expression// show conditional expression ? :

string = (flag != 0) ? “true” : “false” ;

// same as the following if else

if (flag != 0){ string = “true”;}else{ string = “false”;}

Page 78: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 79: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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)

Page 80: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Repetition Statements (cont.)

Page 81: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 82: Data Type, expression & flow of Control 2011-9-16 胡俊峰

initializing;

testing;

altering

Page 83: Data Type, expression & flow of Control 2011-9-16 胡俊峰

C Array — 0 based

Page 84: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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)

Page 85: Data Type, expression & flow of Control 2011-9-16 胡俊峰

while statement (cont.)

Page 86: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 87: Data Type, expression & flow of Control 2011-9-16 胡俊峰

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

Page 88: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Enter at least once, often used in verification

Page 89: Data Type, expression & flow of Control 2011-9-16 胡俊峰

break and continue statements

break statement, used for early termination of a loop

continue statement, used for early continuation of a loop

Page 90: Data Type, expression & flow of Control 2011-9-16 胡俊峰

break;

Page 91: Data Type, expression & flow of Control 2011-9-16 胡俊峰

continue;

Page 92: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 93: Data Type, expression & flow of Control 2011-9-16 胡俊峰

Nested loop

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

Page 94: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 95: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 96: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 97: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 98: Data Type, expression & flow of Control 2011-9-16 胡俊峰
Page 99: Data Type, expression & flow of Control 2011-9-16 胡俊峰

第二次作业:

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