1. 主要内容Contents第一讲 C语言程序设计入门
第二讲 数据类型、运算符和表达式
第三讲 顺序结构
第四讲 选择结构
第五讲 循环结构
第六讲 函数
第七讲 数组与字符串
第八讲 指针
第九讲 结构
第十讲 文件处理
第十一讲 预处理器Program Design in C Language双语课堂Introduction
Data types, operators and expressions
Sequence structure
Selection structure
Repetition structure
Functions
Arrays and strings
Pointers
Structures
File processing
The preprocessor学习程序设计的目的是进行程序设计的基本训练,掌握程序设计的基本方法。
We will learn the C programming language and structured programming techniques.
2. 参考书目ReferencesThe C Programming Language
Brian W. Kernighan
Dennis M. Ritchie
C How to Program
Harvey M. Deitel
Paul J. Deitel
C 语言程序设计
杨健霑
刘英
康卓
Data Structure & Program Design in C
Robert Kruse
Clovis L. Tondo
Bruce P. LeungPROGRAM DESIGN IN C LANGUAGE双语课堂目 录
3. 第一讲 C语言程序设计入门IntroductionProgram Design in C Language双语课堂目 录1.2 C语言的发展C Language's Evolution1.3 结构化程序设计Structured Programming1.4 C程序的基本结构Basic Structure of A C Program1.5 C语言程序的开发C Program Development1.1 计算机基础回顾Review of Computer Basic
4. 计算机系统Computer System计算机(Computer)
能进行计算(computations)和逻辑判断(logical decisions)
在一组指令(instructions)——程序(programs)的控制下处理数据(process data)
硬件(Hardware)
Various devices comprising a computer
Keyboard, screen, mouse, disks, memory, CD-ROM, and processing units
软件(Software)
Programs that run on a computerREVIEW OF COMPUTER BASIC双语课堂目 录第一讲 C语言程序设计入门
5. 计算机的组织Computer Organization计算机包括六大部件:
Input unit(输入单元)
Obtains information from input devices (keyboard, mouse)
Output unit(输出单元)
Outputs information (to screen, to printer, to control other devices)
Memory unit(内存)
Rapid access, low capacity, stores input information
Central processing unit (CPU)(中央处理单元)
Arithmetic and logic unit (ALU)(算术逻辑单元)
Performs arithmetic calculations and logic decisions
Control unit(控制器)
Supervises and coordinates the other sections of the computer
Secondary storage unit(辅助存储器)
Cheap, long-term, high-capacity storage
Stores inactive programsREVIEW OF COMPUTER BASIC双语课堂目 录第一讲 C语言程序设计入门
6. 计算机语言Computer Language三种编程语言(programming language):
机器语言(Machine language)
机器指令(machine instruction)
汇编语言(Assembly language)
类似英文的缩写来表示基本操作(elementary operation)
通过汇编程序(assembler)翻译成机器语言
高级语言(High-level language)
代码(code)类似日常英语
使用数学符号(mathematical notations)
通过编译程序(compiler)翻译成机器语言REVIEW OF COMPUTER BASIC双语课堂目 录第一讲 C语言程序设计入门0110001100000110
0110010111001100
0000110000011011LOAD X
ADD Y
STORE ZZ = X + YMachine LanguageAssembly LanguageHigh-level Language
7. C语言的发展C Language’s EvolutionTraditional C
Evolved by Ritchie from two previous programming languages, BCPL and B
Used to develop UNIX
Used to write modern operating systems
Hardware independent (portable)(可移植)
By late 1970's C had evolved to "Traditional C"
标准化(Standardization)
许多互不兼容(incompatible)的C的变种(variations),差异很小
成立委员会建立 “unambiguous, machine-independent” (明确的,独立于机器的)定义
正式的标准诞生于1989年(C89), 在1999作了重大更新(C99)C LANGUAGE’S EVOLUTION AND FEATURES双语课堂目 录第一讲 C语言程序设计入门
8. 程序概念Program Concept程序的概念
程序是计算机解决问题所需的一系列指令的集合。
A program is a set of self-contained instructions that tells a computer how to solve a problem or carry out a task.
程序=数据结构+算法+程序设计方法+语言工具和编程环境
数据结构(Data structure)是数据的类型和数据的组织形式。
算法(Algorithm)是为解决某个特定的问题而采用的确定且有限的步骤。
程序设计方法(Programming method)
语言工具和编程环境(Language tools and programming environment)STRUCTURED PROGRAMMING双语课堂目 录第一讲 C语言程序设计入门
9. 例1-1 简单程序设计A Simple Program Design问题
求方程ax2+bx+c=0的根(设b2-4ac≥0)
程序设计步骤
定义数据结构
Define data structure
设计算法
Design algorithm
确定程序设计方法
Select a programming method
确定语言和开发环境
Select a computer language and programming environment
实现
ImplementationSTRUCTURED PROGRAMMING双语课堂目 录第一讲 C语言程序设计入门
15. C程序的基本结构Basic Structure of A C ProgramExample 1-3: Hello World
在屏幕上打印一行文字。
Program
BASIC STRUCTURE OF A C PROGRAM双语课堂目 录第一讲 C语言程序设计入门Comments(注释)
Preprocessor directive(预处理命令)
Function(函数)
Statement(语句)
Return 0;(返回语句)/* Example 1-3 (CW01-03.C)
Print a line of text.
This is my first c program.*/
#include
int main()
{
printf("Hello World!");
return 0;
}Hello World!
16. C程序的基本结构Basic Structure of A C Program (Cont.1/5)BASIC STRUCTURE OF A C PROGRAM双语课堂目 录第一讲 C语言程序设计入门/* Example 1-3 (CW01-03.C)
Print a line of text.
This is my first c program.*/
#include
int main()
{
printf("Hello World!");
return 0;
}注释(Comment)
/* 文本 */
不被执行
用来对程序进行描述
17. C程序的基本结构Basic Structure of A C Program (Cont.2/5)BASIC STRUCTURE OF A C PROGRAM双语课堂目 录第一讲 C语言程序设计入门/* Example 1-3 (CW01-03.C)
Print a line of text.
This is my first c program.*/
#include
int main()
{
printf("Hello World!");
return 0;
}预处理命令(Preprocessor directive)
告诉计算机包含某一文件的内容
定义了标准输入/输出操作
18. C程序的基本结构Basic Structure of A C Program (Cont.3/5)BASIC STRUCTURE OF A C PROGRAM双语课堂目 录第一讲 C语言程序设计入门/* Example 1-3 (CW01-03.C)
Print a line of text.
This is my first c program.*/
#include
int main()
{
printf("Hello World!");
return 0;
}函数(Function)
C程序包含一个或多个函数,其中必须有一个 main 函数
圆括号(Parenthesis)指示一个函数
int 表示 main 函数返回(return)一个整数值(integer value)
{ } (braces)包含函数体(body)
}(right brace)表示 main 函数结束
19. C程序的基本结构Basic Structure of A C Program (Cont.4/5)BASIC STRUCTURE OF A C PROGRAM双语课堂目 录第一讲 C语言程序设计入门/* Example 1-3 (CW01-03.C)
Print a line of text.
This is my first c program.*/
#include
int main()
{
printf("Hello World!");
return 0;
}语句(Statement)
一行称为一条语句
必须以 ; ( semicolon )结尾
命令计算机完成一个操作(action)
20. C程序的基本结构Basic Structure of A C Program (Cont.5/5)BASIC STRUCTURE OF A C PROGRAM双语课堂目 录第一讲 C语言程序设计入门/* Example 1-3 (CW01-03.C)
Print a line of text.
This is my first c program.*/
#include
int main()
{
printf("Hello World!");
return 0;
}Return 0;
退出函数的一种方法
21. C程序的开发阶段 Phases of C Program DevelopmentC PROGRAM DEVELOPEMNT双语课堂目 录第一讲 C语言程序设计入门EditPreprocessCompileLinkLoadExecuteEditorProg.cCompilerLinkerCPULoaderProg.objProg.exeRAMLibrariesSource file(源文件)Object file(目标文件)Library file(库文件)Executable file(可执行文件)
22. C程序的开发阶段 Phases of C Program Development (1/4)C PROGRAM DEVELOPEMNT双语课堂目 录第一讲 C语言程序设计入门EditPreprocessCompileLinkLoadExecuteEditorProg.cCompilerLinkerCPULoaderProg.objProg.exeRAMLibrariesEdit(编辑)
Program is created in the editor and stored on disk.
23. C程序的开发阶段 Phases of C Program Development (2/4)C PROGRAM DEVELOPEMNT双语课堂目 录第一讲 C语言程序设计入门EditPreprocessCompileLinkLoadExecuteEditorProg.cCompilerLinkerCPULoaderProg.objProg.exeRAMLibrariesCompile(编译)
Preprocessor program processes the code.
Compiler creates object code and storesit on disk.
24. C程序的开发阶段 Phases of C Program Development (2/4)C PROGRAM DEVELOPEMNT双语课堂目 录第一讲 C语言程序设计入门EditPreprocessCompileLinkLoadExecuteEditorProg.cCompilerLinkerCPULoaderProg.objProg.exeRAMLibrariesLink(链接)
Linker links the object code with the libraries.
25. C程序的开发阶段 Phases of C Program Development (4/4)C PROGRAM DEVELOPEMNT双语课堂目 录第一讲 C语言程序设计入门EditPreprocessCompileLinkLoadExecuteEditorProg.cCompilerLinkerCPULoaderProg.objProg.exeRAMLibrariesExecute(运行)
Loader puts program in memory.
CPU takes each instruction and executes it, possibly storing new data values as the program executes.
26. C程序的开发工具 C Program Development ToolsC PROGRAM DEVELOPEMNT双语课堂目 录第一讲 C语言程序设计入门EditPreprocessCompileLinkLoadExecuteEditorProg.cCompilerLinkerProg.objProg.exeLibrariesIntegrated Development Environment (IDE)(集成开发环境)
Turbo C/C++
Borland C/C++
Visual C/C++IDE
27. 第二讲 数据类型、运算符和表达式Data Types,Operators and ExpressionsPROGRAM DESIGN IN C LANGUAGE双语课堂目 录2.2 变量Variables2.3 数据类型Data Types2.4 常量Constants2.5 整型数据Integers2.1 字符集 标识符 关键字Character Set, Identifiers and Keywords2.7 字符型数据Characters2.8 字符串常量String Constants2.9 算术运算符Arithmetic Operators2.10 类型转换Type Conversion2.6 浮点型数据Floating-point Data2.11 赋值运算符Assignment Operators2.12 逗号运算符Comma Operator
28. 字符集Character SetC 语言源程序文件是来自一个字符集的字符序列。
A C source file is a sequence of characters selected from a character set.
C 语言的字符集(character set)
52个大小写字母(Letters)
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
10个数字(Digits)
0 1 2 3 4 5 6 7 8 9
空格(SPACE)
制表符(Tab)
图形符号(Graphic characters)
! # % ^ & * ( _ ) - + = ~ [ ] ' | \ ; : " {} , . < > / ?CHARACTER SET, IDENTIFIERS AND KEYWORDS双语课堂目 录第二讲 数据类型、运算符和表达式
29. 标识符Identifiers标识符(Identifiers)
是一个字符序列,包括大小写字母(capital and small letters),数字(digits)和下划线(the underscore character)。
用来标识变量名、符号常量名、数组名、函数名、结构名、类型名等。
命名规则
首字符必须是字母或下划线;
一般内部标识符的前31个字符有效,而外部标识符的前6个字符有效;
不能与关键字相同。CHARACTER SET, IDENTIFIERS AND KEYWORDS双语课堂目 录第二讲 数据类型、运算符和表达式i j k
n1 n2 sum
display_matrix
_time1 2x
!here money$
void main integer
date-timeOKInvalid
30. 关键字KeywordsKeywords
The following identifiers are reserved for use as keywords, and may not be used as ordinary identifiers:CHARACTER SET, IDENTIFIERS AND KEYWORDS双语课堂目 录第二讲 数据类型、运算符和表达式auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while
31. 变量Variables变量(Variables)
变量是在程序执行过程中其值会发生变化的量。
Variables are program elements that change their values during the course of program execution.
声明(Declaration)
[,[,...]]
变量在使用之前必须被声明。VARIABLES双语课堂目 录第二讲 数据类型、运算符和表达式int x , y ;
int sum=0 ;
float volt ;
char degree ;变量名(name)是一个标识符变量类型(type)变量可以在声明时被初始化(initialized)
32. 变量与内存Variables and Memory变量与内存(Variables and Memory)
每一个变量有名字(name),类型(type),大小(size)和值(value)
变量名对应于它在内存中的位置(location)
当一个新的值被放进(placed into)变量时,它将替换(replace)掉以前的值
从内存中读取变量的值不会改变它
A visual representationVARIABLES双语课堂目 录第二讲 数据类型、运算符和表达式int x = 23;23FF022BytesRAMx = 90;90printf(“%d”, x);
33. 变量初始化Variables InitializationInitialization
A variable may be initialized in its declaration.
If the variable in question is not automatic, the initialization is done once only, conceptually before the program starts executing, and the initializer must be a constant expression.
Automatic variables for which there is no explicit initializer have undefined values.VARIABLES双语课堂目 录第二讲 数据类型、运算符和表达式char esc = ‘\\’;
int i = 0, limit = MAXLINE+1;
float eps = 1.0e-5;Initializer
35. 基本类型Basic Types基本数据类型(Basic data types):
字符型(char)
a single byte, capable of holding one character
基本整型(int)
an integer, typically reflecting the natural size of integers on the host machine
单精度浮点型(float)
single-precision floating point
双精度浮点型(double)
double-precision floating point
此外,有几个修饰符(qualifiers)可以加到基本数据类型上
short
long
signed
unsignedDATA TYPES双语课堂目 录第二讲 数据类型、运算符和表达式
36. 常量Constants常量(Constants)
常量是在程序执行过程中其值不变化的量。
Constants are program elements that do not change their values during the course of program execution.
C语言有以下几种类型的常量:
整型常量(integer constants)
浮点型常量(floating-point constants)
字符型常量(character constants)
字符串型常量(string constants)CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式
37. 符号常量Symbolic Constants符号常量
符号常量是用一个标识符表示的常量。
定义规则
#define
Symbolic constants are handled by the C preprocessor and are defined using the #define construct. It is a good programming practice to use symbolic constants where possible. This enables certain changes be made with a minimal amount of efforts.CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式#define MAXSIZE 20
#define WELCOME "Welcome to you!"
#define PI 3.14
38. 例2-1 符号常量的应用Symbolic Constants ApplicationProblem
Calculate area of a circle.
ProgramCONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-1 CW02-01.C
Calculate area of a circle.*/
#include
#define PI 3.14
void main() {
float r, area;
scanf("%f",&r);
area = PI*r*r;
printf("area=%f",area);
}1
3.140000arear
39. 整数的类型和大小Integer Types and Sizes在微机中,不同类型的整型数据在内存中占的字节数如下表:Integer VARIABLES AND CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式类型名称类型说明符字节数数值范围基本整型[signed] int2-32768~32767短整型[signed] short [int]2-32768~32767长整型[signed] long [int]4-2147483648~ 2147483647无符号基本整型unsigned [int]20~65535无符号短整型unsigned short [int]20~65535无符号长整型unsigned long [int]40~4294967295
49. 浮点型常量Floating-point Constants有两种形式:
十进制小数
12.3 .65 0.
指数形式:< 小数 > < e | E > < 整数 >
1.2e-2 .1E5 7E0
可以加上后缀 f 或 F 表示float类型,或者 l 或 L 表示long double类型,否则该常量是double类型。
2.3f 1.2L .1E5fFLOATING-POINT VARIABLES AND CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式
50. 例2-3:浮点型变量和常量Floating-point Variables and ConstantsExample 2-3: Floating-point Variables and ConstantsFLOATING-POINT VARIABLES AND CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-3 CW02-03.C
Floating-point variables and constants.*/
#include
void main() {
float f;
double d;
f=33333.33333;
d=33333.3333333333;
printf("f=%f\nd=%f", f, d);
}f=33333.332031
d=33333.333333实数的有效数字是有限的,在有效位之外的数字被舍去。由此可能会产生一些误差。
51. 例2-4:浮点型数据的舍入误差Floating-point Rounding ErrorExample 2-4: Floating-point Rounding ErrorFLOATING-POINT VARIABLES AND CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-4 CW02-04.C
Floating-point rounding error.*/
#include
void main() {
float a, b;
a=123456.789e5;
b=a+20;
printf("a=%f\nb=%f", a, b);
}a=12345678848.000000
b=12345678848.000000???
52. 舍入误差分析Analyze Floating-point Rounding ErrorAnalyze Example 2-4FLOATING-POINT VARIABLES AND CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式a=123456.789e5;
b=a+20;a+20的理论值应该是:12345678920
但是,一个实型变量能够保证的有效数字是7位,后面的数字将被舍去,是没有意义的。
因此,最后得到
b=12345678848.000000由此可知,应当避免一个很大的数和一个很小的数直接相加或相减,否则就会“丢失”较小的数。1.0/3*3=?
53. 字符型常量Character Constants字符型常量
用单引号(single quote)括起来的一个字符。
'x' '9' '+'
转义字符(escape character)
指代一些特殊的字符。CHARACTER VARIABLES AND CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式\a alter(bell) character \\ backslash
\b backspace \? question mark
\f formfeed \' single quote
\n newline \" double quote
\r carriage return \ooo octal number
\t horizontal tab \xhh hexadecimal number
\v vertical tab
54. 例2-5:转义字符Escape CharacterExample 2-5: Escape CharacterCHARACTER VARIABLES AND CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-5 CW02-05.C
Escape character.*/
#include
void main() {
printf(" ab c\t de\rf\tg\n");
printf("h\ti\b\bj k");
}f gde
h j kf ab c gde
h jik输出到显示屏打印机输出
56. 例2-6:字符变量Character VariablesExample 2-6:Character VariablesCHARACTER VARIABLES AND CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-6 CW02-06.C
Assign integers to character variables.*/
#include
void main() {
char c1, c2;
c1=97;
c2=98;
printf("c1=%c,c2=%c\n", c1, c2);
printf("c1=%d,c2=%d", c1, c2);
}c1=a,c2=b
c1=97,c2=98
57. 例2-7:字符变量Character VariablesExample 2-7:Character VariablesCHARACTER VARIABLES AND CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-7 CW02-06.C
Convert lowercase character to uppercase.*/
#include
void main() {
char c1, c2;
c1=97;
c2=c1-32;
printf("c1=%c,c2=%c\n", c1, c2);
}c1=a,c2=A
58. 字符串常量String Constants字符串常量
用双引号(double quote)括起来的字符序列。
"this is a string" "x" "12345"
The double quotes are not part of the string, but only to delimit it. A string constant is actually represented internally as an array of characters terminated by the null character '' (\0).STRING CONSTANTS双语课堂目 录第二讲 数据类型、运算符和表达式‘x’x在内存中占一个字节“x”x在内存中占两个字节\0
60. 算术运算符的优先级Arithmetic Operator Precedence运算符优先级(Operator precedence)
某些运算符先于其他运算符被执行 (例如,先乘除后加减)
必要时可以用()改变计算顺序
Example: Find the average of three variables a, b and c
Do not use: a + b + c / 3
Use: (a + b + c ) / 3
优先级和结合性(precedence and associativity)ARITHMETIC OPERATORS AND EXPRESSIONS双语课堂目 录第二讲 数据类型、运算符和表达式Operator(s)Operation(s)PrecedenceAssociativity()parenthesis1left to right*, /, %Multiplication, division, modulus3left to right+ or -Addition or subtraction4left to right
68. 简单赋值运算符Simple Assignment OperatorSimple assignment operator: =
Associativity:right to left
Examples:ASSIGNMENT OPERATORS AND EXPRESSIONS双语课堂目 录第二讲 数据类型、运算符和表达式c=a+b
a=b=c=d=10
x=(a=5)+(b=8)a=(a+b)
a=(b=(c=(d=10)))
a=5, b=8, x=a+b
69. 复合赋值运算符Compound Assignment OperatorsCompound assignment operator: +=, -=, *=, /=, %=
Associativity:right to left
简化了赋值表达式
表达式格式(form)
=
由下面的表达式简化而来
=
Examples:ASSIGNMENT OPERATORS AND EXPRESSIONS双语课堂目 录第二讲 数据类型、运算符和表达式a+=5
x*=y+7
x+=x-=x*=xa=a+5
x=x*(y+7)
x=x+(x=x-(x=x*x))≡
70. 自增、自减运算符Increment and Decrement Operators自增运算符(Increment operator):++
c++ 可以用来代替 c+=1
自减运算符(Decrement operator):--
c-- 可以用来代替 c-=1
使用形式一:Preincrement
++c or --c
Variable is changed before the expression it is in is evaluated
使用形式二:Postincrement
c++ or c--
Expression executes before the variable is changedINCREMENT AND DECREMENT双语课堂目 录第二讲 数据类型、运算符和表达式
71. 例2-9:自增、自减运算Increment and Decrement OperationExample 2-9: Increment and decrement operationINCREMENT AND DECREMENT双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-9 CW02-09.C
Increment and decrement operation.*/
#include
void main() {
int i=6, a, b;
printf("%d\n", ++i);
printf("%d\n", i++);
a=--i; printf("%d\n", a);
b=i--; printf("%d\n", b);
printf("%d\n", -i++);
printf("i=%d\n", i);
}7
7
7
7
-6i = ?
72. 例2-10:自增、自减运算Increment and Decrement OperationExample 2-10: Increment and decrement operationINCREMENT AND DECREMENT双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-10 CW02-10.C
Increment and decrement operation.*/
#include
void main() {
int i=5, j=5, p, q;
p=(i++)+(i++)+(i++);
q=(++j)+(++j)+(++j);
printf("p=%d,i=%d\n", p, i);
printf("q=%d,j=%d\n", q, j);
}p=15,i=8
q=24,j=8
73. 例2-11:自增、自减运算Increment and Decrement OperationExample 2-11: Increment and decrement operationINCREMENT AND DECREMENT双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-11 CW02-11.C
Increment and decrement operation.*/
#include
void main() {
int i, j, k;
i=1;
j=1;
k=i+++j;
printf("k=%d,i=%d,j=%d\n",k,i,j);
}k=2
i=2
j=1k=(i++)+j;
74. 例2-12:自增、自减运算Increment and Decrement OperationExample 2-12: Increment and decrement operationINCREMENT AND DECREMENT双语课堂目 录第二讲 数据类型、运算符和表达式/* Example 2-12 CW02-12.C
Increment and decrement operation.*/
#include
void main() {
int i=3;
printf("%d,%d\n",i,i++);
}4,3Order of evaluation
79. 算法Algorithm任何计算问题的解决方案包括
按照特定顺序去执行一系列动作(actions)
算法(Algorithm)
为解决某个特定的问题而采用的确定且有限的步骤。
Procedure in terms of
Actions to be executed
The order in which these actions are to be executed
例如 “早晨上学准备算法”:起床-穿衣-洗漱-吃早餐-上学
程序控制(Program Control)
计算机程序中指定语句执行的顺序ALGORITHM双语课堂目 录第三讲 顺序结构算法是程序的灵魂。
Algorithm is the spirit of a program.
80. 算法的表示Representation of Algorithm算法的表示方法
自然语言
Natural language
伪代码
Pseudocode
流程图
Flowchart
计算机语言
Computer languageALGORITHM双语课堂目 录第三讲 顺序结构
84. 算法的计算机语言表示Algorithm (4/4) :Computer Language问题
计算1+2+3+…+100
C语言表示ALGORITHM双语课堂目 录main()
{ int i, sum;
i=1; sum=0;
while (i<=100)
{ sum=sum+i;
i=i+1;
}
printf("1+2+3+...+100=%d",sum);
}第三讲 顺序结构
85. 控制结构Control Structure顺序执行(Sequential execution)
程序中的语句按照它们的书写顺序一句接一句地执行
控制转移(Transfer of control)
把待执行的下一个语句指定为不是书写顺序中的下一个语句
goto语句带来很多问题
程序结构不清晰、可读性差、不利于维护
结构化技术(1970s):所有的程序只用3种结构就可以写出来
顺序结构(Sequence structures)
Built into C
Programs executed sequentially by default
选择结构(Selection structures)
C has three types: if, if-else, and switch
循环结构(Repetition structures)
C has three types: while, do/while and forCONTROL STRUCTURES双语课堂目 录第三讲 顺序结构
87. 顺序结构Sequence StructureSequence Structure
Programs executed sequentially by default
Control flow:
Statements executed one after the other in the order writtenSEQUENCE STRUCTURE双语课堂目 录statement 1statement 2Sequence Structure第三讲 顺序结构
121. 关系表达式的使用 Use Of Relational Expressions问题:写出下面各条件的关系表达式
x为不小于 -5 的整数
x为非零的数
x的平方大于m与n的和ReLATIONAL CALCULATION双语课堂目 录第四讲 选择结构x>=-5
x!=0
x*x>(m+n)
122. if选择结构 The if Selection Structure选择结构(Selection Structure)
用于在可选择的几个操作之间进行选择
伪代码语句举例
If student’s grade is greater than or equal to 60
Print “Passed”
如果条件为真(学生分数大于等于60)
那么就打印或显示“Passed”,然后程序按顺序执行下一条伪代码语句
如果条件为假
就忽略打印或显示操作,顺序执行下一条伪代码语句SELECTION STRUCTURES双语课堂目 录第四讲 选择结构
123. if选择结构 The if Selection Structure选择结构是一个单入/单出结构SELECTION STRUCTURES双语课堂目 录FalsePrint “Passed”grade >= 60Trueif Selection Structureif (grade>=60)
printf(“Passed”);条件判断
可以是任何表达式
0(zero):false
非0(nonzero):true第四讲 选择结构
124. if-else选择结构 The if-else Selection Structureif Selection Structure
只有在条件为真时,才会执行一个操作;否则就会跳过这个操作
if-else Selection Structure
条件为真时所执行的操作与条件为假时所执行的操作不同
伪代码语句举例
If student’s grade is greater than or equal to 60
Print “Passed”
Else
Print “Failed”SELECTION STRUCTURES双语课堂目 录第四讲 选择结构
135. 逻辑表达式的使用 Use Of Logical Expression将下面的条件用C语言的逻辑表达式表达
例1:1≤x≤10且x≠7
x>=1&&x<=10&&x!=7
例2:y能被4整除,但不能被100整除
(y%4==0)&&(y%100!=0)
逻辑与和逻辑非具有短路能力
例1:gender==‘F’&&age>65
如果gender不等于’F’,整个表达式的值就是假,求值过程将停止
例2:average>=90||finalExam>=90
如果average大于等于90,整个表达式的值就是真,求值过程将停止LOGICAL CALCULATION双语课堂目 录第四讲 选择结构
136. 例4-1:逻辑表达式的使用 Use Of Logical Expression问题:任意输入一个字符,判断它是字母还是数字。LOGICAL CALCULATION双语课堂目 录第四讲 选择结构void main() {
char c;
c=getchar();
if ((c>=‘A’&&c<=‘Z’)||(c>=‘a’&&c<=‘z’))
printf(“%c is a letter.”, c);
else if (c>=‘0’&&c<=‘9’)
printf(“%c is a digit.”, c);
else
printf(“%c is neither a letter nor a digit.”, c);
} /*CW04-01.C*/
137. 多重选择结构Multiple-Selection Structureswitch
在判断过程中,一个变量或表达式会分别针对其可能会取的每个整型常量值进行测试,并采取不同的动作MULTIPLE-SELECTION STRUCTURE双语课堂目 录第四讲 选择结构switch(expression)
{ case : action_1; [break;]
case : action_2; [break;]
……
case :action_n-1; [break;]
[default: action_n; [break;]]
}
138. 例4-2:多重选择结构Multiple-Selection Structure问题
根据考试成绩的等级打印相应的分数段MULTIPLE-SELECTION STRUCTURE双语课堂目 录第四讲 选择结构grade=getchar();
switch(grade)
{ case ‘A’: printf(“85~100\n”);
case ‘B’: printf(“70~84\n”);
case ‘C’: printf(“60~69\n”);
case ‘D’: printf(“<60\n”);
default: printf(“error\n”);
}若grade=‘A’
85~100
70~84
60~69
<60
error
143. 例4-4:多重选择结构Multiple-Selection Structure代码(cw04-04.c)MULTIPLE-SELECTION STRUCTURE双语课堂目 录第四讲 选择结构main()
{ int op1, op2, operator;
scanf("%d%d", &op1, &op2); operator=getchar();
switch(operator)
{ case ‘+’: printf(“=%d”, op1+op2); break;
case ‘-’: printf(“=%d”, op1-op2); break;
case ‘*’: printf(“=%d”, op1*op2); break;
case ‘/’: printf(“=%d”, op1/op2); break;
default: printf(“operator is invalid!”);
}
}
144. 例4-4:多重选择结构Multiple-Selection Structure(cont.)改进代码MULTIPLE-SELECTION STRUCTURE双语课堂目 录第四讲 选择结构main()
{ int op1, op2, operator, result, done=1;
scanf("%d%d", &op1, &op2); operator=getchar();
switch(operator)
{ case ‘+’: result=op1+op2; break;
case ‘-’: result=op1-op2; break;
case ‘*’: result=op1*op2; break;
case ‘/’: result=op1/op2; break;
default: done=0;
}
if (done) printf(“%d%c%d=%d”, op1, operator, op2, result);
else printf(“operator is invalid!”);
} /*CW04-04.C*/标记变量(flag)
145. 例4-5:多重选择结构Multiple-Selection Structure问题 根据输入的月份,给出当月的天数。MULTIPLE-SELECTION STRUCTURE双语课堂目 录第四讲 选择结构main()
{ int m, d,year;
scanf(“%d,%d", &year,&m);
switch (m) {
case 1: case 3: case 5: case 7: case 8: case 10: case
12: d=31; break;
case 4: case 6: case 9: case 11: d=30; break;
case 2: if(year%4==0&&year%100!=0||year%400==0) d=29;
else d=28; break;
default: d=0;
}
d>0 ? printf("%d", d) : printf("invalid input!");
} /*CW04-05.C*/
147. 第五讲 循环结构Repetition StructuresPROGRAM DESIGN IN C LANGUAGE双语课堂目 录5.2 计数器控制的循环Counter-controlled structure5.3 标记控制的循环Flag-controlled stucture5.4 嵌套的控制结构Nested control structures5.5 do-while循环结构The do-while repetition5.1 while循环结构The while repetition structure5.6 for循环结构The for repetition structure5.7 结构化程序设计小结Structured programming summary5.8 程序设计举例Examples
148. while循环结构 The while Repetition Structure循环结构(Repetition Structure)
程序员指定当某个条件一直为真时重复执行某个动作
Example in Pseudocode:
While there are more items on my shopping list
Purchase next item and cross it off my list
如果条件“购物单上还有其他商品”为真时,就执行动作“购买下一个商品,并把它从购物单上划掉”
如果该条件一直为真,这个动作就会重复执行
最终,该条件为假,循环过程就会终止,程序将执行这个循环结构之后的第一个伪代码语句
while 循环重复执行,直到条件为假THE While REPETITION STRUCTURE双语课堂目 录第五讲 循环结构
149. while循环结构 The while Repetition Structurewhile 语句
while (condition) action;
Example in C:THE While REPETITION STRUCTURE双语课堂目 录第五讲 循环结构int product=2;
while (product<=1000)
product=2*product;product<=1000product=2*productYN可以是两种语句
单语句
复合语句while 循环结构是单入/单出结构
153. 计数器控制的循环 Counter-Controlled RepetitionExample 5-1
ResultCOUNTER-CONTROLLED REPETITION双语课堂目 录第五讲 循环结构Enter grade:60
Enter grade:70
Enter grade:65
Enter grade:76
Enter grade:73
Enter grade:56
Enter grade:78
Enter grade:64
Enter grade:89
Enter grade:76
Class average is 70
158. 标记控制的循环 Flag-Controlled RepetitionExample 5-2(cw05-02.c)
FLAG-CONTROLLED REPETITION双语课堂目 录第五讲 循环结构#include
void main() {
float average;
int counter, grade, total;
total = 0;
counter = 0;
printf("Enter grade, -1 to end:");
scanf("%d", &grade);
while (grade != -1) {
total += grade;
counter++;
printf("Enter grade, -1 to end:");
scanf("%d", &grade);
}新的类型初始化处理结束判断
159. 标记控制的循环 Flag-Controlled RepetitionExample 5-2(cw05-02.c)
FLAG-CONTROLLED REPETITION双语课堂目 录第五讲 循环结构 if (counter != 0) {
average = (float)total / counter;
printf("Class average is %.2f\n", average);
}
else
printf("No grades were entered\n");
}Enter grade, -1 to end:70
Enter grade, -1 to end:60
Enter grade, -1 to end:65
Enter grade, -1 to end:-1
Class average is 65.00结束
160. 嵌套的控制结构 Nested Control Structures构造程序的方式
堆叠控制结构(stacking)
嵌套控制结构(nesting)
Example 5-3
每班10个学生期末考试结果的清单(1-通过,2-没有通过)
开发出一程序对结果进行分析
如果有8个学生通过,显示“优秀班级”
分析
程序每次执行处理10个考试结果
采用计数器控制的循环
使用两个统计计数器
一个统计通过的人数,另一个统计没通过的人数
每一个考试结果要么是1,要么是2
只对1进行测试,不是1的其他数就假定为2NESTED CONTROL STRUCTURES双语课堂目 录第五讲 循环结构
161. 嵌套的控制结构 Nested Control Structures算法的顶部
分析考试结果,判断是否评为优秀班级
细化
初始化变量
输入10个考试结果,并计算通过考试和未通过考试的学生数目
显示考试结果的汇总,并判断是否应该评为优秀班级
进一步细化
初始化变量NESTED CONTROL STRUCTURES双语课堂目 录第五讲 循环结构通过数初始化为0
未通过数初始化为0
循环控制计数器初始化为1
162. 嵌套的控制结构 Nested Control Structures进一步细化(续)
输入10个考试结果,并计算通过考试和未通过考试的学生数目NESTED CONTROL STRUCTURES双语课堂目 录第五讲 循环结构While 循环控制计数器的值<=10
输入一个考试结果
if 考试结果为1
通过计数器加1
else
未通过计数器加1
循环控制计数器加1
163. 嵌套的控制结构 Nested Control Structures进一步细化(续)
显示考试结果的汇总,并判断是否应该评为优秀班级NESTED CONTROL STRUCTURES双语课堂目 录第五讲 循环结构显示通过考试的学生数目
显示未通过考试的学生数目
If 8个以上的学生通过了考试
显示“优秀班级”
164. 嵌套的控制结构 Nested Control StructuresExample 5-3(cw05-03.c)NESTED CONTROL STRUCTURES双语课堂目 录第五讲 循环结构#include
void main() {
int passed=0, failed=0, counter=1, result;
while (counter<=10) {
printf("Enter result (1=pass, 2=fail):");
scanf("%d", &result);
if (result==1)
passed++;
else
failed++;
counter++;
}
165. 嵌套的控制结构 Nested Control StructuresExample 5-3(cw05-03.c)NESTED CONTROL STRUCTURES双语课堂目 录第五讲 循环结构 printf("Passed %d\n", passed);
printf("Failed %d\n", failed);
if (passed>8)
printf("Excellent Class\n");
}Enter result (1=pass, 2=fail):1
Enter result (1=pass, 2=fail):1
Enter result (1=pass, 2=fail):1
Enter result (1=pass, 2=fail):2
Enter result (1=pass, 2=fail):1
Enter result (1=pass, 2=fail):1
Enter result (1=pass, 2=fail):1
Enter result (1=pass, 2=fail):1
Enter result (1=pass, 2=fail):1
Enter result (1=pass, 2=fail):1
Passed 9
Failed 1
Excellent Class
166. do-while循环结构 The do-while Repetition Structuredo-while 语句
do
action
while (condition);THE do-While REPETITION STRUCTURE双语课堂目 录第五讲 循环结构conditionactionYNdo-while 循环结构是单入/单出结构先执行循环体语句,再判断循环条件
167. do-while循环结构 The do-while Repetition StructureExample 5-4(cw05-04.c)
计算1+2+…+100THE do-While REPETITION STRUCTURE双语课堂目 录第五讲 循环结构#include
void main() {
int s, i;
s=0;
i=1;
do {
s = s + i;
i++;
} while (i<=100);
printf("1+2+...+100=%d\n", s);
}
168. do-while与while do-while and while比较do-while与while(cw05-05.c)THE do-While REPETITION STRUCTURE双语课堂目 录第五讲 循环结构main()
{ int s=0, n;
scanf(“%d”, &n);
while (n<=2)
{ s += n; n++; }
printf(“s=%d,n=%d”, s, n);
}main()
{ int s=0, n;
scanf(“%d”, &n);
do { s += n; n++; }
while (n<=2);
printf(“s=%d,n=%d”, s, n);
}1
s=3,n=33
s=0,n=31
s=3,n=33
s=3,n=41212
169. for循环结构 The for Repetition Structurefor 语句
for (设置初值; 条件判断; 设置增减量)
{ ………
循环主体语句;
}THE FOR REPETITION STRUCTURE双语课堂目 录第五讲 循环结构没有分号条件判断循环主体语句YN设置增减量设置初值其他语句
170. for循环结构 The for Repetition Structurefor 循环结构能够自动处理计数器控制的循环的细节
THE FOR REPETITION STRUCTURE双语课堂目 录第五讲 循环结构#include
void main() {
int counter;
for (counter = 1; counter <= 10; counter++)
printf("%d ", counter);
} /*cw05-06b.c*/循环条件控制变量增1对控制变量进行初始化1 2 3 4 5 6 7 8 9 10
171. for循环结构 The for Repetition Structurefor 语句使用说明
for ([expression1]; [expression2]; [expression3])
action;
Notes:
三个表达式都是可选的(都可以为空)
如果表达式2为空,那么就假定该循环条件为真
因此会创建一个无限循环THE FOR REPETITION STRUCTURE双语课堂目 录第五讲 循环结构for (i=0;;i++)
printf(“%2d”,i);for (i=0;1;i++)
printf(“%2d”,i);=
172. for循环结构 The for Repetition Structurefor 语句使用说明
for ([expression1]; [expression2]; [expression3])
action;
Notes:
表达式1和表达式3可以是任何合法的表达式
常用逗号表达式THE FOR REPETITION STRUCTURE双语课堂目 录第五讲 循环结构for (s=0,i=1;i<=100;i++)
s+=i;for (s=0,i=1;i<=100;s+=i,i++);
对多个变量初始化修改多个变量的值
173. do-while循环结构 The do-while Repetition StructureExample 5-4(cw05-04.c)
计算1+2+…+100THE do-While REPETITION STRUCTURE双语课堂目 录第五讲 循环结构#include
void main() {
int s, i;
s=0;
i=1;
do {
s = s + i;
i++;
} while (i<=100);
printf("1+2+...+100=%d\n", s);
}
174. 嵌套循环for语句的嵌套循环ExampleTHE do-While REPETITION STRUCTURE双语课堂目 录第五讲 循环结构#include
int main(void)
{
int i, j;
int n=6;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
printf("*");
printf("\n");
}
return 0;
}输出图形
175. break语句 The break Statementbreak 语句
break;
当在while、do-while、for或switch结构中执行break语句时,break语句会造成程序从该结构中退出
程序接着执行该结构之后的第一条语句
常规应用:
提前从循环结构中退出
跳过switch结构的剩余部分THE BREAK AND CONTINUE STATEMENTS双语课堂目 录第五讲 循环结构
176. break语句 The break StatementExample: break (cw05-07.c)
THE BREAK AND CONTINUE STATEMENTS双语课堂目 录第五讲 循环结构#include
void main() {
int x;
for (x = 1; x <= 10; x++) {
if (x == 5)
break;
printf("%d ", x);
}
printf("\nBroke out of loop at x == %d\n", x);
}1 2 3 4
Broke ot of loop at x == 5
177. break语句 The break StatementExample: break in switch and for structure
THE BREAK AND CONTINUE STATEMENTS双语课堂目 录第五讲 循环结构for (i=1;i<=3;i++)
{ switch(i)
{ case 1: printf(“*\n”);
break;
case 2: printf(“**\n”);
break;
case 3: printf(“***\n”);
break;
}
}*
**
***for (i=1;i<=3;i++)
{ if (i==1) {printf(“*\n”);
break;}
if (i==2) {printf(“**\n”);
break;}
if (i==3) {printf(“***\n”);
break;}
}
}
*
178. continue语句 The continue Statementcontinue 语句
continue;
当在while、do-while或for结构中执行continue语句时,continue语句能够跳过该结构中剩余语句
执行下一个循环过程
Notes:
在while和do-while结构中
在continue语句被执行之后立即进行循环条件的测试
在for结构中
表达式3被执行之后,然后进行循环条件的测试THE BREAK AND CONTINUE STATEMENTS双语课堂目 录第五讲 循环结构
179. continue语句 The continue StatementExample: continue (cw05-08a.c, cw05-08b.c)
THE BREAK AND CONTINUE STATEMENTS双语课堂目 录第五讲 循环结构#include
void main() {
int x;
x = 1;
while (x <= 10) {
if (x = = 5)
continue;
printf("%d ", x);
x++;
}
}1 2 3 4#include
void main() {
int x;
for (x = 1; x <= 10; x++) {
if (x = = 5)
continue;
printf("%d ", x);
}
}1 2 3 4 6 7 8 9 10
181. goto语句 The goto StatementExample: goto (cw05-09.c)
THE GOTO STATEMENTS双语课堂目 录第五讲 循环结构#include
void main() {
int s=0, i=1;
Loop:
s = s + i;
i++;
if (i<=100) goto Loop;
printf("1+2+...+100=%d\n", s);
}1 2 3 4
Broke ot of loop at x == 5语句标号
182. 结构化程序设计Structured ProgrammingStructured programming
Disciplined approach to writing programs
Easier than unstructured programs to understand, test, debug, and modify programs
Rules for structured programming
Only single-entry/single-exit control structures are used
Rules:
1. Begin with the “simplest flowchart”
2. Any rectangle (action) can be replaced by two rectangles (actions) in sequence
3. Any rectangle (action) can be replaced by any control structure
4. Rules 2 and 3 can be applied in any order and multiple timesSTRUCTURED PROGRAMMING SUMMARY双语课堂目 录第五讲 循环结构
185. 结构化程序设计规则Rules for Structured Programming (1/2)Rule 1 and 2STRUCTURED PROGRAMMING SUMMARY双语课堂目 录Rule 1: Begin with the simplest flowchartRule 2: Any rectangle can be replaced by two rectangles in sequence第五讲 循环结构Rule 2Rule 2Rule 2
186. 结构化程序设计规则Rules for Structured Programming (2/2)Rule 3: Any rectangle can be replaced by any control structureSTRUCTURED PROGRAMMING SUMMARY双语课堂目 录Rule 3Rule 3Rule 3第五讲 循环结构
188. 结构化程序设计小结Structured Programming SummaryAll programs can be broken down into 3 control structures:
Sequence: handled automatically by compiler
Selection: if, if-else or switch
Repetition: while, do-while or for
Can only be combined in two ways:
Stacking (rule 2)
Nesting (rule 3)
Any selection can be rewritten as an if statement,
and any repetition can be rewritten as a while statementSTRUCTURED PROGRAMMING SUMMARY双语课堂目 录第五讲 循环结构
189. 结构化程序设计举例Example 5-10问题
求下面公式的前n项之和
分析
累加求和: s = s + an
关键在于写出 an 的表达式
用计数器控制的循环实现STRUCTURED PROGRAMMING EXAMPLES 双语课堂目 录第五讲 循环结构初始化累计和变量 s 为0
初始化计数器变量 i 为1
输入要累加的项数,放入变量 n
While i <= n
计算第n项的值,结果放入an
累计,s = s + an
修改计数器变量,i++
输出结果 s
192. 结构化程序设计举例Example 5-11问题
用下面的公式求π的近似值(直到最后一项的绝对值小于10-6为止):
分析
先计算等式右边的和
累加求和: s = s + an
当|an|<10-6时,停止累加
用标记控制的循环实现STRUCTURED PROGRAMMING EXAMPLES 双语课堂目 录第五讲 循环结构初始化累计和变量 s 为0
初始化计数器变量 i 为1
第1项的值 an = 1
While |an| >= 10-6
累计,s = s + an
计算第n项的值,结果放入an
计算π=s*4
输出结果 π
196. 结构化程序设计举例Example 5-12实现(cw05-12.c)
STRUCTURED PROGRAMMING EXAMPLES 双语课堂目 录第五讲 循环结构#include
void main() {
int i, d, max, min;
printf("Input 10 integers:\n");
scanf("%d", &d);
max=min=d;
for (i=2;i<=10;i++) {
scanf("%d", &d);
if (d>max) {max=d; continue;}
if (d
197. 结构化程序设计举例Example 5-13问题
判断整数 m 是否素数
实现(cw05-13.c)
STRUCTURED PROGRAMMING EXAMPLES 双语课堂目 录第五讲 循环结构#include
#include
void main() {
int m, k, i;
scanf("%d", &m);
k=sqrt(m);
for (i=2;i<=k;i++) if (m%i==0) break;
if (i>k) printf("%d is a prime number.\n", m);
else printf("%d is not a prime number.\n", m);
}
198. 结构化程序设计举例Example 5-14问题
找出1-100间的全部素数
实现(cw05-14.c)
STRUCTURED PROGRAMMING EXAMPLES 双语课堂目 录第五讲 循环结构#include
#include
void main() {
int m, k, i;
for (m=1;m<=100;m++) {
k=sqrt(m);
for (i=2;i<=k;i++)
if (m%i==0) break;
if (i>k) printf("%4d", m);
}
}Example 5-13nesting
204. 结构化程序设计举例Example 5-17实现(cw05-17a.c)
STRUCTURED PROGRAMMING EXAMPLES 双语课堂目 录第五讲 循环结构main()
{ int m, n;
for (n=1;n<=5;n++)
{ for (m=1;m<=5-n;m++) printf(" ");
for (m=1;m<=2*n-1;m++) printf("*");
printf("\n");
}
}
205. 结构化程序设计举例Example 5-17实现(cw05-17b.c)
STRUCTURED PROGRAMMING EXAMPLES 双语课堂目 录第五讲 循环结构main() {
int m, n;
for (n=1;n<=5;n++) {
for (m=1;m<=5-n;m++)
printf(" ");
for (m=1;m<=2*n-1;m++)
printf("*");
printf("\n");
} for (n=4;n>=1;n--) {
for (m=1;m<=5-n;m++)
printf(" ");
for (m=1;m<=2*n-1;m++)
printf("*");
printf("\n");
}
}
221. 举例:函数的定义Example: Function Definitions举例:函数定义(cw06-02.c)
Function definitions 双语课堂目 录第六讲 函数#include
int maximum(int, int, int);
void main() {
int a, b, c;
printf("enter three integers: ");
scanf("%d%d%d", &a, &b, &c);
printf("Maximum is: %d", maximum(a, b, c));
}
int maximum(int x, int y, int z) {
int max = x;
if (y>max) max = y;
if (z>max) max = z;
return max;
}maximumintintintint函数原型
227. 函数调用Function Call函数调用(function call)
激发函数(invoking functions)
提供函数名和参数(argument)
函数完成指定的任务
函数可以返回结果(result)
类比
老板命令工人去完成一项任务
工人获取信息,完成任务,返回报告
“隐藏”(hiding):老板不知道细节Program modules in c 双语课堂目 录第六讲 函数BossWorker1Worker2Worker3 Worker4Worker5主调函数函数调用被调函数
228. 函数调用Function Call函数调用的执行过程
Function call 双语课堂目 录第六讲 函数main() {
int a, b, c;
scanf("%d%d", &a, &b);
c = max(a, b);
printf("the larger is %d", c);
}126int max(int a, int b) {
int c;
c=a>=b?a:b;
return c;
}3451、……
2、主调函数暂停,
3、把实参的值拷贝给形参,控制权传给函数 max 。
4、……5、结束被调函数,把函数值返回给主调函数,同时把控制权还给主调函数。
6、……
229. 参数传递Passing Parameters函数间的数据传递
参数(传递)
结果(返回)Function call 双语课堂目 录第六讲 函数int max(int a, int b) {
…… return c;
}
main() {
…… c=max(a, b);
}max()abcmain()参数传递返回值传递
230. 按值调用和按引用调用Call By Value And Call By Reference调用函数的两种途径
按值调用
把参数的值的副本传递给函数
在函数内改变参数的值不会影响调用函数中的参数的原始值
如果函数不需要修改参数的值,就采用这种调用方式
按引用调用
把参数传递给函数
在函数内改变参数的值将改变参数的原始值
用于可信的函数
在C语言中,所有调用都是按值调用Function call 双语课堂目 录第六讲 函数
231. 形参和实参Formal Parameter and Actual Parameter形参和实参
Function call 双语课堂目 录第六讲 函数int max(int a, int b)
{ int c=a>=b?a:b;
return c;
}
main()
{ int a, b, c;
scanf(“%d%d”, &a, &b);
c=max(a, b);
}形式参数
简称“形参”。在函数定义时表示可以接受实际参数的值实际参数
简称“实参”。在函数调用时给出
232. 形参Formal Parameter形参
Function call 双语课堂目 录第六讲 函数int max(int a, int b)
{ int c=a>=b?a:b;
return c;
}
main()
{ int a, b, c;
scanf(“%d%d”, &a, &b);
c=max(a, b);
}只有在函数被调用、启动后,才临时为其分配存储单元,并接受主调函数传来的数据。
在函数调用结束后,形参所占存储单元被释放。
233. 实参Actual Parameter实参
Function call 双语课堂目 录第六讲 函数int max(int a, int b)
{ int c=a>=b?a:b;
return c;
}
main()
{ int a, b, c;
scanf(“%d%d”, &a, &b);
c=max(a, b);
}实参是函数调用时主调函数传送给被调函数的参数的实际值。
实参可以是常量、变量和表达式。
实参必须有确定的值。
234. 参数传递Passing Parameters实参和形参应该一一对应
Function call 双语课堂目 录第六讲 函数int max(int a, int b)
{ int c=a>=b?a:b;
return c;
}
main()
{ int x=6, y;
y=max(x, x++);
printf(“%d”, y);
}当实参表列中有多个实参时,对实参的求值顺序并不确定。
Turbo C是按从右往左的顺序求值。b=x++;
a=x;7在参数传递时
235. 参数传递Passing Parameters值传递
Function call 双语课堂目 录第六讲 函数int max(int a, int b)
{ int c=a>=b?a:b;
a++; b++;
return c;
}
main()
{ int x=6, y=5, z;
z=max(x, y);
printf(“%d,%d,%d”,x,y,z);
}实参与形参不共用存储单元。
参数传递时,把实参的值复制一份给形参。
形参值的变化不影响实参的值。
所以,形参和实参可以同名。6,5,66x5y6a5b
236. 参数传递Passing Parameters实参和形参的类型应该相同或赋值兼容
Function call 双语课堂目 录第六讲 函数int max(int a, int b)
{ int c=a>=b?a:b;
return c;
}
main()
{ int x=6, y=5, z;
z=max(x, y);
printf(“%d”, z);
}如果a, b是整型,则调用合法;
如果a, b是字符型,因为字符型与整型可以互换,所以也是合法的;
如果a, b是短整型,则进行类型自动转换,结果也正确;
如果a或b是实数,则结果有可能不正确。b=y;
a=x;在参数传递时
237. 函数返回值Returning Results函数返回值的类型应该与函数的类型一致
如果不一致,以函数类型为准,对返回值进行类型转换Function call 双语课堂目 录第六讲 函数int max(int a, int b)
{ float c=a>=b?a:b;
return c;
}
main()
{ int x=6, y=5, z;
z = 2*max(x, y);
printf(“%d”, z);
}c 的类型?
返回值的类型?max(x,y) 的类型?
2*max(x,y) 的类型?
253. 汉诺塔问题 Towers Of Hanoi递归问题举例:汉诺塔
设计
move 函数:移动一个盘
把盘 n 从 s 塔移到 d 塔
hanoi 函数:移动n个盘的汉诺塔问题
把 n 个盘从 x 塔移到 z 塔,y 塔作为辅助塔Recursion 双语课堂目 录第六讲 函数void move(int n, char s, char d);
void hanoi(int n, char x, char y, char z);
254. 汉诺塔问题 Towers Of Hanoi递归问题举例:汉诺塔
实现(cw06-06.c)
Recursion 双语课堂目 录第六讲 函数#include
void move(int n, char s, char d);
void hanoi(int n, char x, char y, char z);
void main() {
int n;
printf("\t Input the number of disks:");
scanf("%d", &n);
hanoi(n, 'X', 'Y', 'Z');
}
255. 汉诺塔问题 Towers Of Hanoi递归问题举例:汉诺塔
实现(cw06-06.c)
Recursion 双语课堂目 录第六讲 函数void hanoi(int n, char x, char y, char z) {
if (n==1) move(n, x, z);
else {
hanoi(n-1, x, z, y);
move(n, x, z);
hanoi(n-1, y, x, z);
}
}
void move(int n, char s, char d) {
printf("\t%d\t%c-->%c\n", n, s, d);
}
266. 程序块作用范围Block Scope程序块作用范围
在程序块内声明的变量,在程序块内被引用
函数体内声明的变量,函数的参数,程序块内的变量Scope 双语课堂目 录第六讲 函数int max(int x, int y) {
…
}
void main() {
int a;
…
{ int a;
…
}
…
}作用范围
从声明的位置开始,到程序块的右大括号隐藏
同名变量,内部变量“隐藏了”外部变量
267. 函数原型作用范围Function Prototype Scope函数原型作用范围
函数原型中的参数Scope 双语课堂目 录第六讲 函数int max(int x, int y);
void main() {
…
}
int max(int x, int y) {
…
}
268. 存储类别与作用范围Storage Classes And Scope举例:存储类别与作用范围(cw06-08.c)
Scope 双语课堂目 录第六讲 函数#include
void a(void); /*function prototype*/
void b(void); /*function prototype*/
void c(void); /*function prototype*/
int x = 1; /*global variable*/
void main() {
int x = 5;
printf("local x in outer scope of main is %d\n", x);
{ /*start new scope*/
int x = 7;
printf("local x in inner scope of main is %d\n", x);
} /*end new scope*/
printf("\nlocal x in outer scope of main is %d\n", x);
269. 存储类别与作用范围Storage Classes And Scope举例:存储类别与作用范围(cw06-08.c)
Scope 双语课堂目 录第六讲 函数 a();
b();
c();
a();
b();
c();
printf("local x in main is %d\n", x);
}
void a() {
int x = 25; /*initialized each time a is called*/
printf("\nlocal x in a is %d after entering\n", x);
x++;
printf("local x in a is %d before exiting\n", x);
}
270. 存储类别与作用范围Storage Classes And Scope举例:存储类别与作用范围(cw06-08.c)
Scope 双语课堂目 录第六讲 函数void b() {
static int x = 50; /*static initialization only*/
/*first time b is called*/
printf("\nlocal x in b is %d after entering\n", x);
x++;
printf("local x in b is %d before exiting\n", x);
}
void c() {
printf("\nglobal x is %d on entering c\n", x);
x*=10;
printf("global x is %d on exiting c\n", x);
}
271. 存储类别与作用范围Storage Classes And Scope举例:存储类别与作用范围(cw06-08.c)
Scope 双语课堂目 录第六讲 函数local x in outer scope of main is 5
local x in inner scope of main is 7
local x in outer scope of main is 5
local x in a is 25 after entering a
local x in a is 26 before exiting a
local x in b is 50 after entering b
local x in b is 51 before exiting b
global x is 1 on entering c
global x is 10 on exiting c
272. 存储类别与作用范围Storage Classes And Scope举例:存储类别与作用范围(cw06-08.c)
Scope 双语课堂目 录第六讲 函数local x in a is 25 after entering a
local x in a is 26 before exiting a
local x in b is 51 after entering b
local x in b is 52 before exiting b
global x is 10 on entering c
global x is 100 on exiting c
local x in main is 5
292. 第七讲 数组与字符串 Arrays and StringsPROGRAM DESIGN IN C LANGUAGE双语课堂目 录7.2 数组Arrays7.3 查找与排序Searching and sorting7.4 多维数组Multiplr subscripted arrays7.5 字符串Strings7.1 简介Introduction
293. 简介IntroductionArrays(数组)
Data Structures of related data items
Static entity(静态实体)
same size throughout programIntroduction双语课堂目 录第七讲 数组与字符串6572837997877957…78
299. 使用数组Using ArraysExample:数组的输入与输出
Ayrrays双语课堂目 录第七讲 数组与字符串#include
int main(void)
{int i,score[5];
for (i=0; i<=4; i++)
{
printf(“Input score:”);
scanf(“%d”,&score[i]);
}
printf(”***Output***”);
for (i=0; i<=4; i++)
printf(“score[%d]=%d\n", i,score[i]);
return 0;
}
300. 使用数组Using ArraysExample:将数组中的最大值及最小值输出
Ayrrays双语课堂目 录第七讲 数组与字符串 #include
int main()
{ int A[5]={74,48,30,89,62};
int i,min,max;
min=max=A[0];
printf("elements in arrray A are ");
for(i=0;i<5;i++)
{printf("%d ",A[i]);
if(A[i]>max) max=A[i];
if (A[i]
301. 使用数组Using ArraysExample:数组查找
Ayrrays双语课堂目 录第七讲 数组与字符串#define SIZE 6
int main()
{ int i,num,flag=0;
int A[SIZE]={33,75,69,41,33,19};
scanf(“%d“,&num);
for(i=0;i
310. for (roll=1; roll<=1000; roll++) {
face = rand()%6+1;
frequency[face]++;
}
printf("%s%17s\n", "Face", "Frequency");
for (face=1; face<=SIZE-1; face++)
printf("%4d%17d\n", face, frequency[face]);
}使用数组Using ArraysExample:Using Arrays(cw07-03.c)
Ayrrays双语课堂目 录第七讲 数组与字符串
311. 使用数组Using ArraysExample:Using Arrays(cw07-04.c)
把一个任意的正整数 N 转换成 d 进制数
用 N 除以 d,
如果商不为 0,继续用商除以 d,直到商为 0
用数组 remainder 保存每一步的余数Ayrrays双语课堂目 录第七讲 数组与字符串NN/8N%8134816841682102125202
312. #include
#define MAX 10
void main() {
int N, d, len;
int remainder[MAX];
printf("Input a decimal integer and a base:");
scanf("%d%d", &N, &d);
printf("Converting...\n");使用数组Using ArraysExample:Using Arrays(cw07-04.c)
Ayrrays双语课堂目 录第七讲 数组与字符串
313. len=0;
while (N) {
len++;
remainder[len]=N%d;
N=N/d;
}
printf("equals ");
for (;len>0;len--) printf("%d",remainder[len]);
}使用数组Using ArraysExample:Using Arrays(cw07-04.c)
Ayrrays双语课堂目 录第七讲 数组与字符串
329. 把数组传递给函数Passing Arrays to Functions把数组元素传递给函数
数组元素就是一个普通的变量
按值传递(call-by-value)
Example: Passing arrays and elements to functions
(cw07-06.c)Passing Ayrrays To Functions双语课堂目 录第七讲 数组与字符串#include
void modifyArray(int [], int);
void modifyElement(int);
void main() {
int a[] = {0, 1, 2, 3, 4}, i;
330. 把数组传递给函数Passing Arrays to FunctionsExample:(cw07-06.c)Passing Ayrrays To Functions双语课堂目 录第七讲 数组与字符串 printf("\nThe values of the original array are:\n");
for (i=0;i
331. 把数组传递给函数Passing Arrays to FunctionsExample:(cw07-06.c)Passing Ayrrays To Functions双语课堂目 录第七讲 数组与字符串void modifyArray(int array[], int size) {
int j;
for (j=0;j
332. 把数组传递给函数Passing Arrays to FunctionsExample:(cw07-06.c)Passing Ayrrays To Functions双语课堂目 录第七讲 数组与字符串The values of the original array are:
0 1 2 3 4
The values of the modified array are:
0 2 4 6 8
The value of a[3] is 6
Value in modifyElement is 12
The value of a[3] is 6
335. 顺序查找Sequential SearchingExample: Sequential searching(cw07-07.c)
Sequential Searching双语课堂目 录第七讲 数组与字符串#define N 10
void main() {
int list[N+1]={0,65,72,83,79,97,87,75,57,91,78};
int key,i;
printf("Input search key:");
scanf("%d",&key);
for (i=1;(list[i]!=key)&&(i<=N);i++);
if (i>N) printf("Not found!");
else printf("Success! The position is %d.",i);
}
341. 数据插入Insert DataExample: Inserting data
(cw07-09.c)Directive Insert Sorting双语课堂目 录第七讲 数组与字符串#include
#define N 20
void main()
{ int i, j, x, len=9;
int list[N]={57,65,72,75,78,79,87,91,97};
printf("Sorted list:\n");
for (i=0;i
342. 数据插入Insert DataExample: Inserting data
(cw07-09.c)Directive Insert Sorting双语课堂目 录第七讲 数组与字符串 for (i=0;(x>list[i])&&(ii;j--) list[j]=list[j-1];
list[i]=x;
len++;
printf("The new list:\n");
for (i=0;i
344. 直接插入排序Directive Insert SortingExample: directive insert sorting
(cw07-10.c)Directive Insert Sorting双语课堂目 录第七讲 数组与字符串#include
#define N 10
void main()
{ int i, j, k, len;
int list[N], x;
printf("Input several integers to construct a list:");
scanf("%d", &len);
for (i=0;i
345. 直接插入排序Directive Insert SortingExample: directive insert sorting
(cw07-10.c)Directive Insert Sorting双语课堂目 录第七讲 数组与字符串 printf("\nTo sort...\n");
for (i=1;ilist[j])&&(jj;k--) list[k]=list[k-1];
list[j]=x;
}
printf("Finished! The list has been sorted:\n");
for (i=0;i
347. 简单选择排序Simple Selection SortingExample: Simple selection sorting
(cw07-12.c)Simple Selection Sorting双语课堂目 录第七讲 数组与字符串#include
#define N 10
void main()
{ int i, j, len, min;
int list[N], tmp;
printf("Input several integers to construct a list:");
scanf("%d", &len);
for (i=0;i
348. 简单选择排序Simple Selection SortingExample: Simple selection sorting
(cw07-12.c)Simple Selection Sorting双语课堂目 录第七讲 数组与字符串 printf("\nTo sort...\n");
for (i=0;ilist[j]) min=j;
tmp=list[i]; list[i]=list[min]; list[min]=tmp;
}
printf("Finished! The list has been sorted:\n");
for (i=0;i
349. 简单选择排序Simple Selection SortingExample: Simple selection sorting
(cw07-12.c)Simple Selection Sorting双语课堂目 录第七讲 数组与字符串 printf("\nTo sort...\n");
for (i=0;ilist[j]) min=j;
tmp=list[i]; list[i]=list[min]; list[min]=tmp;
}
printf("Finished! The list has been sorted:\n");
for (i=0;i
351. 冒泡排序Bubble SortingExample: Bubble sorting
(cw07-11.c)Bubble Sorting双语课堂目 录第七讲 数组与字符串#include
#define N 10
void main()
{ int i, j, len;
int list[N], tmp;
printf("Input several integers to construct a list:");
scanf("%d", &len);
for (i=0;i
352. 冒泡排序Bubble SortingExample: Bubble sorting
(cw07-11.c)Bubble Sorting双语课堂目 录第七讲 数组与字符串 printf("\nTo sort...\n");
for (i=0;ilist[j+1]) {
tmp=list[j]; list[j]=list[j+1]; list[j+1]=tmp;
}
printf("Finished! The list has been sorted:\n");
for (i=0;i
358. 字符串StringsCharacters(字符)
Character constant
An int value represented as a character in single quotes
'z' represents the integer value of z
Strings(字符串)
Series of characters treated as a single unit
Can include letters, digits and special characters (*, /, $)
String constant
written in double quotes
"Hello"STRINGS双语课堂目 录第七讲 数组与字符串
385. 程序设计举例Programming ExamplesExample: TicTacToe
(tictac.c)PROGRAMMING EXAMPLES双语课堂目 录第七讲 数组与字符串char matrix[3][3]; /* the ticktacktoe matrix */
void main(void) {
char done;
printf("This is the game of ticktacktoe.\n");
printf("You will be playing against the computer.\n");
done = ' ';
init_matrix();done
保存当前游戏的状态和结局
386. 程序设计举例Programming ExamplesExample: TicTacToe
(tictac.c)PROGRAMMING EXAMPLES双语课堂目 录第七讲 数组与字符串 do {
disp_matrix();
get_player_move();
done = check(); /* see if winner */
if (done != ' ') break; /* winner! */
get_computer_move();
done = check(); /* see if winner */
} while (done == ' ');
if (done == 'X') printf("You won!\n");
else printf("I won!!!!\n");
disp_matrix(); /* show final positions */
}
387. 程序设计举例Programming ExamplesExample: TicTacToe
(tictac.c)PROGRAMMING EXAMPLES双语课堂目 录第七讲 数组与字符串/* Initialize the matrix. */
void init_matrix(void) {
int i, j;
for (i=0; i<3; i++)
for (j=0; j<3; j++)
matrix[i][j] = ' ';
}
388. 程序设计举例Programming ExamplesExample: TicTacToe
(tictac.c)PROGRAMMING EXAMPLES双语课堂目 录第七讲 数组与字符串/* Get a player's move. */
void get_player_move(void) {
int x, y;
printf("Enter X, Y coordinates for your move: ");
scanf("%d%*c%d", &x, &y);
x--; y--;
if (matrix[x][y] != ' ') {
printf("Invalid move, try again.\n");
get_player_move();
}
else matrix[x][y] = 'X';
}
389. 程序设计举例Programming ExamplesExample: TicTacToe (tictac.c)
PROGRAMMING EXAMPLES双语课堂目 录第七讲 数组与字符串/* Get a move from the computer. */
void get_computer_move(void) {
int i, j;
for (i=0; i<3; i++) {
for (j=0; j<3; j++)
if (matrix[i][j] == ' ') break;
if (matrix[i][j] == ' ') break;
}
if (i*j == 9) {
printf("draw\n");
exit(0);
}
else
matrix[i][j] = 'O';
}
390. 程序设计举例Programming ExamplesExample: TicTacToe
(tictac.c)PROGRAMMING EXAMPLES双语课堂目 录第七讲 数组与字符串/* Display the matrix on the screen. */
void disp_matrix(void) {
int t;
for (t=0; t<3; t++) {
printf(" %c | %c | %c",
matrix[t][0], matrix[t][1], matrix[t][2]);
if (t != 2) printf("\n---|---|---\n");
}
printf("\n");
}
391. 程序设计举例Programming ExamplesExample: TicTacToe
(tictac.c)PROGRAMMING EXAMPLES双语课堂目 录第七讲 数组与字符串/* See if there is a winner. */
char check(void) {
int i;
for (i=0; i<3; i++) /* check rows */
if (matrix[i][0] == matrix[i][1] &&
matrix[i][0] == matrix[i][2])
return matrix[i][0];
for (i=0; i<3; i++) /* check colums */
if (matrix[0][i] == matrix[1][i] &&
matrix[0][i] == matrix[2][i])
return matrix[0][i];
393. 第八讲 指针 PointersPROGRAM DESIGN IN C LANGUAGE双语课堂目 录8.2 指针变量Pointer variables8.7 指针数组Arrays of pointers8.8 指针的指针Pointers to pointers8.9 函数指针Pointers to functions8.1 简介Introduction8.4 指针参数Pointer arguments8.3 指针运算符Pointer operators8.6 指针与数组Pointers and arrays8.5 指针表达式和运算Pointer expressions and arithmetic8.10 指针函数Pointer functions
394. 简介IntroductionPointers
Powerful, but difficult to master
Simulate call-by-reference
Close relationship with arrays and strings
Create and control dynamic data structures
List, queue, stack and treeTHE POINTERS 双语课堂目 录第八讲 指针
395. 指针和地址Pointers and Addresses指针就是变量的地址
THE POINTERS 双语课堂目 录第八讲 指针int x;
x=23;内存单元的地址
一个常量,就是指向变量的指针。变量名
其实就是符号化的内存单元地址。内存单元的内容
就是变量的值。FF00x23直接引用
Direct reference
通过变量名直接引用变量的值
396. 指针变量Pointer Variables指针变量就是包含内存地址的变量
THE POINTERS 双语课堂目 录第八讲 指针int x=23;
int *x_pointer;
x_pointer=&x;FF00x23FFF0x_pointerFF00指针变量
保存变量的地址。
变量 x_pointer 的值是变量 x 的地址(指针)。
目前,指针 x_pointer 指向变量 x 。间接引用
Indirect reference
通过指针间接引用变量的值
399. 指针运算符Pointer Operators&(address operator,地址运算符)
Returns address of operandTHE POINTERS 双语课堂目 录第八讲 指针int y, *yPtr;
y = 5;
yPtr = &y;5yPtrfff0yff00yPtry5Address of y is value of yPtryPtr “points to” yff00
400. 指针运算符Pointer Operators*(indirective operator,间接运算符,指针运算符)
Returns a alias of what its operand points to
*yPtr returns y (because yPtr points to y)
可以用在赋值语句中THE POINTERS 双语课堂目 录第八讲 指针int y=5, *yPtr;
yPtr = &y;int y, *yPtr;
yPtr = &y;
*yPtr = 5;
401. 指针运算符举例Example: Pointer OperatorsExample: Pointer operators (cw08-01.c)
THE POINTERS 双语课堂目 录第八讲 指针#include
void main() {
int a, *aPtr;
a = 7;
aPtr = &a;
printf("The address of a is %p"
"\nThe value of aPtr is %p", &a, aPtr);
printf("\n\nThe value of a is %d"
"\nThe value of *aPtr is %d", a, *aPtr);
printf("\n\nShowing that * and & are inverses of each other."
"\n&*aPtr = %p"
"\n*&aPtr = %p", &*aPtr, *&aPtr);
}
402. 指针运算符举例Example: Pointer OperatorsExample: Pointer operators (cw08-01.c)
运行结果THE POINTERS 双语课堂目 录第八讲 指针The address of a is 1A58
The value of aPtr is 1A58
The value of a is 7
The value of *aPtr is 7
Showing that * and & are inverses of each other.
&*aPtr = 1A58
*&aPtr = 1A58* 和 & 是互反的
411. 指针与函数举例Example: Pointer ArgumentsExample: call by value
(cw08-02a.c)THE POINTERS 双语课堂目 录第八讲 指针#include
int callByValue(int);
void main() {
int number = 5;
printf("The original value of number is %d", number);
number = callByValue(number);
printf("\nThe new value of number is %d", number);
}
int callByValue(int n) {
return n*n*n;
}The original value of number is 5
The new value of number is 125
412. 指针与函数举例Example: Pointer ArgumentsExample: call by reference with pointer arguments
(cw08-02b.c)THE POINTERS 双语课堂目 录第八讲 指针#include
void callByReference(int*);
void main() {
int number = 5;
printf("The original value of number is %d", number);
callByReference(&number);
printf("\nThe new value of number is %d", number);
}
void callByReference(int *nPtr) {
*nPtr = *nPtr**nPtr**nPtr;
}The original value of number is 5
The new value of number is 125
413. 指针与函数举例Example: Pointer ArgumentsExample: call by reference with pointer arguments
分析THE POINTERS 双语课堂目 录第八讲 指针void main() {
int number = 5;
callByReference(&number);
}void callByReference(int *nPtr) {
*nPtr = *nPtr**nPtr**nPtr;
}void main() {
int number = 5;
callByReference(&number);
}void callByReference(int *nPtr) {
*nPtr = *nPtr**nPtr**nPtr;
}void main() {
int number = 5;
callByReference(&number);
}void callByReference(int *nPtr) {
*nPtr = *nPtr**nPtr**nPtr;
}nPtr5numbernPtr125numbernPtr125number调用前调用后返回
414. 指针与函数举例Example: Pointer ArgumentsExample: swap the values of two arguments
THE POINTERS 双语课堂目 录第八讲 指针void swap(int x, int y) {
int tmp;
tmp=x; x=y; y=tmp;
}
void main() {
int a=3, b=5;
swap(a, b);
printf("a=%d,b=%d",a,b);
}a=3,b=5void swap(int *x, int *y) {
int tmp;
tmp=*x; *x=*y; *y=tmp;
}
void main() {
int a=3, b=5;
swap(&a, &b);
printf("a=%d,b=%d",a,b);
}a=5,b=3
418. 指针与数组的关系The Relationship Between Pointers and Arrays引用数组元素的方法小结
数组和指针几乎可以互换使用THE POINTERS 双语课堂目 录第八讲 指针main() {
int i, a[5]={1,2,3,4,5};
for (i=0; i<5; i++)
printf("%2d",a[i]);
}下标法main() {
int i, a[5]={1,2,3,4,5};
for (i=0; i<5; i++)
printf("%2d",*(a+i));
}地址法main() {
int a[5]={1,2,3,4,5}, *p;
for (p=a; p<(a+5); p++)
printf("%2d",*p);
}指针法
419. 指针与数组的关系The Relationship Between Pointers and Arrays数组和指针互换使用中的注意事项
THE POINTERS 双语课堂目 录第八讲 指针因为a是数组名,即数组的首地址,它的值在程序运行期间是固定不变的!
是一个常量指针。错main() {
int a[5]={1,2,3,4,5}, *p;
for ( p=a; a<(p+5); a++ )
printf("%2d",*a);
}
420. 指针与数组的关系The Relationship Between Pointers and Arrays数组和指针互换使用中的注意事项
THE POINTERS 双语课堂目 录第八讲 指针要注意指针变量的当前值。ppa[0]a[1]a[2]a[3]a[4]数组amain() {
int i, a[5], *p;
p=a;
for ( i=0; i<5; i++ )
scanf( "%d", p++ );
for ( i=0; i<5; i++, p++ )
printf( "%d ", *p );
}错p = a;
421. 指针与数组的关系The Relationship Between Pointers and Arrays数组和指针互换使用中的注意事项
注意运算符的优先级THE POINTERS 双语课堂目 录第八讲 指针* aPtr ++* (aPtr ++)等价考虑:
*(aPtr++) 与 *(++aPtr)int a=0, *aPtr=&a;
printf("a=%d,aPtr=%p\n", a, aPtr);
printf("%d\n", *aPtr++);
printf("a=%d,aPtr=%p\n", a, aPtr);a=0,aPtr=1BCC
0
a=0,aPtr=1BCE
422. 指针与数组的关系The Relationship Between Pointers and Arrays举例:数组和指针的互换使用
按引用调用的冒泡排序THE POINTERS 双语课堂目 录第八讲 指针void sort( int *x , int n) {
…
}
void main() {
int a[10];
…
…
sort( a , 10);
…
}a, xa[0]a[1]a[2]a[3]a[4]a[5]a[6]a[7]a[8]a[9]地址
428. 指针数组Arrays Of Pointers举例:洗牌和发牌的模拟
定义数据结构
字符串(指针)数组 suit 保存牌的花色名
字符串(指针)数组 face 保存牌的号码
二维数组 deck 表示一副牌,行对应花色,列对应号码
保存洗牌后牌的序号THE POINTERS 双语课堂目 录第八讲 指针deck[ 2 ][ 12 ] represents the King of ClubsHeartsDiamondsClubsSpades0
1
2
3
Ace
Two
Three
Four
Five
Six
Seven
Eight
Nine
Ten
Jack
Queen
King
0
1
2
3
4
5
6
7
8
9
10
11
12
Clubs
King
434. 指针数组Arrays Of Pointers举例:洗牌和发牌的模拟
实现(cw08-05.c)THE POINTERS 双语课堂目 录第八讲 指针void shuffle(int wDeck[][13]) {
int row, column, card;
for (card=1; card<=52; card++) {
do {
row = rand()%4;
column = rand()%13;
} while(wDeck[row][column]!=0);
wDeck[row][column]=card;
}
}
435. 指针数组Arrays Of Pointers举例:洗牌和发牌的模拟
实现(cw08-05.c)THE POINTERS 双语课堂目 录第八讲 指针void deal(int wDeck[][13], char *wFace[], char *wSuit[]) {
int card, row, column;
for (card=1; card<=52; card++)
for (row=0; row<4; row++)
for (column=0; column<13; column++)
if (wDeck[row][column]==card)
printf("%5s of %-8s%c",
wFace[column], wSuit[row],
card%2==0?'\n':'\t');
}
436. 第九讲 结构 StructuresPROGRAM DESIGN IN C LANGUAGE双语课堂目 录9.2 结构定义Structure definitions9.3 初始化结构Initializing structures9.5 在函数中使用结构Using structures with functions9.6 结构数组Arrays of structures9.1 简介Introduction9.7 链表Linked list9.4 访问结构成员Accessing structure members
437. 简介IntroductionStructures(结构)
Collections of related variables
Can contain variables of different data types
Commonly used to define records to be stored in files
Combined with pointers, can create linked lists, stacks, queues, and treesSTRUCTURES 双语课堂目 录第九讲 结构
440. 结构定义Structure Definitions结构定义说明
相同结构的成员名不可以相同
不同结构的成员名可以相同,不互相冲突STRUCTURE DEFINITIONS双语课堂目 录第九讲 结构struct date { int year,month,day; };
struct Book {
char title[50],writer[20],publisher[50];
int year,month;
};
int year,month,day;
441. 结构定义Structure Definitions结构定义说明
结构的成员可以使基本类型和构造类型(数组和其他结构)STRUCTURE DEFINITIONS双语课堂目 录第九讲 结构struct date {
int year,month,day;
};
struct StuRec {
int num;
char name[20];
struct date birthday;
};
449. 访问结构成员Accessing Structure MembersExample: Accessing structure members
(cw09-01.c)ACCESSING MEMBERS OF STRUCTURES双语课堂目 录第九讲 结构#include
struct card {
char *face;
char *suit;
};
void main() {
struct card a, *aPtr;
a.face = "Ace";
a.suit = "Spades";
aPtr = &a;与数组的不同:
结构变量名不是指针
450. 访问结构成员Accessing Structure MembersExample: Accessing structure members
(cw09-01.c)ACCESSING MEMBERS OF STRUCTURES双语课堂目 录第九讲 结构 printf("%s%s%s\n%s%s%s\n%s%s%s\n",
a.face, " of ", a.suit,
aPtr->face, " of ", aPtr->suit,
(*aPtr).face, " of ", (*aPtr).suit);
}Ace of Spades
Ace of Spades
Ace of Spades注意:
结构不能作为整体输入输出
必须逐个成员进行输入输出
451. 在函数中使用结构Using Structures With Functions把结构的单个成员传递给函数
按值调用传递
被调用函数不能修改调用函数中的结构成员
把整个结构传递给函数
按值调用传递
被调用函数不能修改调用函数中的结构
把结构指针传递给函数
按引用调用传递
被调用函数能修改调用函数中的结构USING STRUCTURES WITH FUNCTIONS双语课堂目 录第九讲 结构
452. 在函数中使用结构Using Structures With FunctionsExample: Passing structures to functions
编写函数实现结构的复制(cw09-02.c)USING STRUCTURES WITH FUNCTIONS双语课堂目 录第九讲 结构#include
struct date {
int year, month, day;
};
void show(char *, struct date);
void copy(struct date, struct date);
void clone(struct date, struct date *);
void main() {
struct date d1, d2, d3, d4;
d1.year = 2004;
d1.month = 5;
d1.day = 1;
show("d1", d1);
454. 在函数中使用结构Using Structures With FunctionsExample: Passing structures to functions
编写函数实现结构的复制(cw09-02.c)USING STRUCTURES WITH FUNCTIONS双语课堂目 录第九讲 结构void copy(struct date s, struct date d) {
d = s;
}
void clone(struct date s, struct date *dPtr) {
*dPtr = s;
}d1: 2004-5-1
d2: 2004-5-1
d3: 0-0-24
d4: 2004-5-1
455. 在函数中使用结构Using Structures With Functions把整个结构返回
因为结构变量之间可以赋值
按值调用把数组传递给函数
把数组作为结构的成员,然后把结构传递给函数
被调用函数不能修改调用函数中的数组USING STRUCTURES WITH FUNCTIONS双语课堂目 录第九讲 结构
456. 定义类型的别名typedeftypedef
为已经定义的数据类型创建一个别名(或同义词)
举例
创建了一个新的类型名 Date ,它是 struct date 的别名
注意:并没有创建新的类型
可以简化程序代码,提高程序的可移植性TYPEDEF双语课堂目 录第九讲 结构typedef struct date Date;void show(char *, Date d);
void copy(Date s, Date d);typedef int Integer;
458. 结构数组Arrays Of Structures结构数组
数组的元素是结构
常用结构来表示记录,那么结构数组就可以表示一组记录
举例
全班 N 个学生,每个学生有学号、姓名、四门课的成绩ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构学号姓名成绩1成绩2成绩3成绩4101WangHai80787681102ZhaoFei68667175………………………………130LiRui82768184
459. 结构数组Arrays Of Structures结构数组
举例
全班 N 个学生,每个学生有学号、姓名、四门课的成绩
那么,可以定义结构数组来保存 N 个学生的数据
这样,每个学生的数据就对应一个结构(一条记录),便于编程处理ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构struct student {
int num;
char name[20];
float scores[4];
};
struct student students[30];
460. 结构数组Arrays Of Structures举例:高性能洗牌和发牌仿真程序
修改原来的数据结构
用一个纸牌结构数组保存一副牌
纸牌的花色和号码名依然保存在字符串数组中
这样,数组中的纸牌俨然已有一个顺序了,则可以改进算法
洗牌:随机打乱纸牌在数组中的位置
不存在无限延期
发牌:按纸牌在数组中的顺序显示输出
数组遍历一次ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构
463. 结构数组Arrays Of Structures举例:高性能洗牌和发牌仿真程序
实现(cw09-03.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构void fillDeck(Card *wDeck, char *wFace[], char *wSuit[]) {
int i;
for (i=0; i<=51; i++) {
wDeck[i].face = wFace[i%13];
wDeck[i].suit = wSuit[i/13];
}
}
464. 结构数组Arrays Of Structures举例:高性能洗牌和发牌仿真程序
实现(cw09-03.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构void shuffle(Card *wDeck) {
int i, j;
Card temp;
for (i=0; i<=51; i++) {
j = rand()%52;
temp = wDeck[i];
wDeck[i] = wDeck[j];
wDeck[j] = temp;
}
}
465. 结构数组Arrays Of Structures举例:高性能洗牌和发牌仿真程序
实现(cw09-03.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构void deal(Card *wDeck) {
int i;
for (i=0; i<=51; i++) {
printf("%5s of %-8s%c",
wDeck[i].face,
wDeck[i].suit,
(i+1)%2 ? '\t' : '\n');
}
}
466. 结构数组Arrays Of Structures举例:检索
某班有 n 个学生,每个学生的数据包括学号、姓名、年龄和性别。要求给定任意一个学号,程序能输出检索的结果,并显示对应的学生的数据。(cw09-04.c)
分析
用结构体数组保存学生数据
采用顺序查找法ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构输入学生信息输入查询条件查找学生信息,报告结果
467. 结构数组Arrays Of Structures举例:检索
实现(cw09-04.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构#include
#define MAX 20
void main() {
struct StuRec {
int num;
char name[20];
char gender;
int age;
} student[MAX];
int i, N, num;
468. 结构数组Arrays Of Structures举例:检索
实现(cw09-04.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构 printf("\tInput a integer as the number of students:");
scanf("%d", &N);
printf("\tInput %d students' information:\n",N);
printf("\n\tNo.\tName\tGender\tAge\n");
for (i=0;i
469. 结构数组Arrays Of Structures举例:检索
实现(cw09-04.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构 printf("\n\tInput a number:");
scanf("%d", &num);
printf("\n\tPlease wait. Searching...\n");
for (i=0;i
470. 结构数组Arrays Of Structures举例:检索
增加要求:可以多次查找(cw09-04m.c)
ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构输入学生信息输入查询条件查找学生信息,报告结果是否继续查询YN
471. 结构数组Arrays Of Structures举例:检索
修订后的部分代码(cw09-04m.c)
ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构 do {
scanf("%d", &num);
for (i=0;i
472. 结构数组Arrays Of Structures举例:点票程序
有三个候选人,N个选举人,每次输入一个得票的候选人的名字,要求最后输出各人的得票结果。
定义数据结构ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构struct candidate {
char name[20]; /*姓名*/
int count; /*得票数*/
} cand[3];
473. 结构数组Arrays Of Structures举例:点票程序
算法ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构输入候选人信息输入选票查找得票人信息找到否?得票人的票数增一输出点票结果点完否?YNNY
474. 结构数组Arrays Of Structures举例:点票程序
实现(cw09-05.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构……
do {
printf("Vote:\t"); gets(name);
for (i=0;i
475. 结构数组Arrays Of Structures举例:改进点票程序
假设选举人都可以是候选人
分析点票过程中数组的变化ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构litaolitao wanghai litao zhaofei ……litaowanghailitaowanghaizhaofei
476. 结构数组Arrays Of Structures举例:改进的点票程序
数据结构和算法ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构struct candidate {
char name[20];
int count;
} cand[M];输入选票查找得票人信息找到否?得票人的票数增一输出点票结果点完否?YNNY加入新的候选人;
其得票数赋值“1”。
477. 结构数组Arrays Of Structures举例:改进的点票程序
实现(cw09-06.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构。。。
printf("Vote:\t"); gets(name); found=0;
for (i=0;i
478. 结构数组Arrays Of Structures举例:增强点票程序
要求按候选人得票数
从高到低顺序输出结果。
修改算法ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构输入选票查找得票人信息找到否?得票人的票数增一输出点票结果点完否?YNNY加入新的候选人;
其得票数赋值“1”。按得票数进行排序
479. 结构数组Arrays Of Structures举例:增强点票程序
实现(cw09-07.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构…
for (i=0;i
480. 结构数组Arrays Of Structures举例:优化点票程序
如果候选人的信息较多,为了提高排序过程中数据交换的性能,增设一数组order,用来保存排序结果。
分析ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构01234530514220Wanghai M 43 P …12Zhaofei F 41 P …6Lilan F 38 N …35Huangjin M 52 P …9Wuma M 29 N …15Hecheng M 36 P …order的初态order的末态从高到低0
1
2
3
4
5
481. 结构数组Arrays Of Structures举例:优化点票程序
实现(cw09-08.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构 for (i=0;i
482. 结构数组Arrays Of Structures举例:优化点票程序
实现(cw09-08.c)ARRAYS OF STRUCTURES双语课堂目 录第九讲 结构 for (i=0;i
483. 数据结构Data StructuresDynamic data structures(动态数据结构)
Data structures that grow and shrink during execution
Linked lists(链表)
Allow insertions and removals anywhere
Stacks(栈)
Allow insertions and removals only at top of the stack
Queues(对列)
Allow insertions at the back and removals from the frontLINKED LISTS双语课堂目 录第九讲 结构
489. 链表Linked ListsExample: Linked list
主函数LINKED LISTS双语课堂目 录第九讲 结构void insert(ListNodePtr*, int);
int delete(ListNodePtr*, int);
int isEmpty(ListNodePtr);
void printList(ListNodePtr);
void menu(void);
void main() {
ListNodePtr listPtr = NULL;
int choice;
int item;
menu();
printf("? ");
scanf("%d", &choice);
490. 链表Linked ListsExample: Linked list
主函数LINKED LISTS双语课堂目 录第九讲 结构 while (choice != 3) {
switch (choice) {
case 1:
printf("Enter an integer: ");
scanf("%d", &item);
insert(&listPtr, item);
printList(listPtr);
break;
491. 链表Linked ListsExample: Linked list
主函数LINKED LISTS双语课堂目 录第九讲 结构 case 2:
if (!isEmpty(listPtr)) {
printf("Enter an integer to be deleted: ");
scanf("%d", &item);
if (delete(&listPtr, item)) {
printf("%d deleted.\n", item);
printList(listPtr);
}
else
printf("%d not found.\n", item);
}
else
printf("List is Empty!\n");
break;
493. 链表Linked ListsExample: Linked list
显示菜单函数LINKED LISTS双语课堂目 录第九讲 结构void menu(void) {
printf("Enter your choice:\n"
"1 to insert an element into the list.\n"
"2 to delete an element from the list.\n"
"3 to ent.\n");
}
494. 链表Linked ListsExample: Linked list
插入结点函数LINKED LISTS双语课堂目 录第九讲 结构2042listPtr35newPtrprePtrcurPtr
506. 第十讲 文件处理 File ProcessingPROGRAM DESIGN IN C LANGUAGE双语课堂目 录10.2 文件和流Files and streams10.3 顺序存取文件Sequential access files10.4 随机存取文件Random access files10.5 举例Examples10.1 简介Introduction
507. 简介IntroductionData files(数据文件)
Can be created, updated, and processed by C programs
Are used for permanent storage of large amounts of data
Storage of data in variables and arrays is only temporaryFILE PROCESSING 双语课堂目 录第十讲 文件处理
517. 第十一讲 预处理器 The PreprocessorPROGRAM DESIGN IN C LANGUAGE双语课堂目 录11.2 文件包含The #include preprocessor directive11.3 符号常量The #define preprocessor directive: symbolic constants11.4 宏The #define preprocessor directive: macro11.5 条件编译Conditional compilation11.1 简介Introduction
518. 简介Introduction预处理(preprocessing)
Occurs before a program is compiled
Inclusion of other files
Definition of symbolic constants and macros
Conditional compilation of program code
Conditional execution of preprocessor directives
预处理命令(preprocessor directive)的格式
Lines begin with #
Only whitespace characters before directives on a line The Preprocessor 双语课堂目 录第十一讲 预处理器
519. 文件包含The #include Preprocessor Directive#include
Copy of a specified file included in place of the directive
#include
Searches standard library for file
Use for standard library files
#include "filename"
Searches current directory, then standard library
Use for user-defined files
Used for:
Programs with multiple source files to be compiled together
Header file – has common declarations and definitions (classes, structures, function prototypes)
#include statement in each fileThe Preprocessor 双语课堂目 录第十一讲 预处理器
520. 符号常量The #define Preprocessor Directive: symbolic constants#define
Preprocessor directive used to create symbolic constants and macros
Symbolic constants
When program compiled, all occurrences of symbolic constant replaced with replacement text
Format
#define identifier replacement-text
Example
Everything to right of identifier replaces text
Cannot redefine symbolic constants once they have been createdThe Preprocessor 双语课堂目 录第十一讲 预处理器#define PI 3.14159#define PI = 3.14159