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

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

Introduction to C Programming
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
CS1061 C Programming Lecture 5: Building Blocks of Simple Programs A. O’Riordan, 2004.
Lecture 02 Data Types, Conversions if Statements METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan.
Data types and variables
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
JavaScript, Fourth Edition
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
1 Chapter Four Boolean Expressions and Control Statements.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
Chapter 2 Getting Started in C Programming
A First Book of ANSI C Fourth Edition
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Outline Variables 1.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
C Tokens Identifiers Keywords Constants Operators Special symbols.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Input, Output, and Processing
Chapter 2: Using Data.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Lesson 6 Getting Started in C Programming Hu Junfeng 2007/10/10.
1 Hu Junfeng 2015/09/23 第三讲 语言 数据类型 流程控制 函数. 关于选课和免修.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
CONSTANTS Constants are also known as literals in C. Constants are quantities whose values do not change during program execution. There are two types.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Chapter 2 Variables.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
By Mr. Muhammad Pervez Akhtar
Variables Symbol representing a place to store information
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
Chapter 3 Selection Statements §3.1 The Boolean Type and Operators §3.2 The if-else Statements §3.3 Case Studies §3.4 Logical Operators §3.5 Switch Statements.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
C++ for Engineers and Scientists Second Edition
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 2 Variables.
ECE Application Programming
Introduction to C Programming
Chapter 8 JavaScript: Control Statements, Part 2
Introduction to C Programming
Chapter 2 Variables.
Chapter 2 Variables.
Introduction to C Programming
Presentation transcript:

Data Type, expression & flow of Control 胡俊峰

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

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

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

5 Integer Data Types (continued)

6 Data types (integer type) Data type size ( bit ) range of values short int K ~ 32K-1 ( ~ 32767) int32-2G ~ 2G-1 Unsigned short1664K -1 ~ 0 unsigned 324G-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  indicates a double literal  9.234f indicates a float literal  9.234L indicates a long double literal

11 Floating –point encoding Floating-point numbers consist of an ``exponent,'' ``significand'', and ``sign bit'' sign bit 1 Exponent 7significand 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 (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 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 Mixed-mode expression (automatic type conversion)

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

Relational Expressions integer (char) float double Same Type 0 false not 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 && R

Truth table of || (or) b1 || b

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!=0 0 1 year%400== Is leap year: y%4 == 0 && (y%100 != 0 || y%400 == 0) Input a year y%100 != 0  y%100 No zero  true Zero  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() arg1arg2 … conversion Contral string: “%d;%f; %c” arg3 5; ;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() function display 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() arg1arg2 … conversion Contral string: “%d;%f; %c” arg A

scanf() function

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

Selection selection is a single-entry/single-exit structure: execute only when condition is satisfied. true false Relational expression 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 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 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”

if.. else if chain else if if exp1 exp3 exp2 else if case1 case2case3case4

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 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 楼机房上机。 地点:中厅。 上机内容,届时见课程网站。