21T2 9024-Week 01
目录
printf
Loops
Functions
Data Types
Aggregate Data Types
Arrays
scanf and atoi
Arrays and Functions
Multi-dimensional Arrays
Defining New Data Types
Structures
Abstract Data Types 抽象数据类型
Stack 堆栈,LIFO 后进先出
Compilers 编译器
Summary
CSE
gcc prog.c
ls -lt
./a.out
gcc -Wall prog.c // show all warnings
gcc -o gcd prog.c //give a.out a new name
printf
printf(format-string, expr...);
format-string
%d decimal
%f floating-point
%c character
%s string
\n new line
\" quotation mark
printf("%8.3f\n", 3.14159)
3.142
for k = 6
k++;//k=k+1
n=k--; //assign k to n, then decrement k by 1
// k=6 n=7
++k;///increment k by 1, afterwards, k=7;
n=--k; // first drcrement k by 1, then assign k to n
//k=6 n=6
if()
{statements;
}if()
{statements 1;
}
else
{statements 2;
}
Conditionals
int main()
{int x,y;if((x>y) && !(y-x <= 0)) //前为真则后不为真/前假后真{printf("Aye\n");}else{printf("Nay\n"); // final result}
}
int main()
{int x;x= (x >= 0) + (x < 0);printf("%d\n",x);
}// always 1. true-printf 1, false 0, always 0+1 or 1+0
Loops
while loop /more common
while (expression){
statements;
}
do...while loop
do {
statements;
} while (expression); // at least do the loop once
for loop
for (expr1;expr2;expr3){
statements;
}
expr1 before loop starts
expr2 check if the loop can contine
expr3 how to caculate at thhe end of this loop
Exercise 4-output
int main()
{
int i, j;
for (i = 8; i > 1; i /= 2) {for (j = i; j >= 1; j--) {printf("%d%d\n", i, j);}printf("\n");
}
}
Functions
return-type function-name(parameters) {declarationsstatementsreturn …; }
如果return_type为void,则函数不返回值
如果parameters为void,则函数没有参数
Fuctions always return something
return=函数最后输出
Data Types
char 'A'
int 2, -17
float 3.14159
double 3.14159265358979
Aggregate Data Types
all elements have same base type eg:char s[50]; int v[100]
combine different base types eg:struct student { char name[30]; int zID; }
Arrays
size N, valid subscripts are 0...N-1
Examples
int a[20];
char b[10];
我们可以在文件的顶部定义一个符号常量
#define SPEED_OF_LIGHT 299792458.0 #define ERROR_MESSAGE "Out of memory.\n"
C Coding Style Guide (http://wiki.cse.unsw.edu.au/info/CoreCourses/StyleGuide)
数组初始化
char s[6] = {'h', 'e', 'l', 'l', 'o', '\0'}; char t[6] = "hello"; int fib[20] = {1, 1};//fib[0]=fib[1]=1, fib[2]未定义 int vec[] = {5, 4, 3, 2, 1};
Exercise #5-output
#include <stdio.h>
int main(void) {int arr[3] = {10,10,10};char str[] = "Art";// str[3]=A r t \0int i;for (i = 1; i < 3; i++) {arr[i] = arr[i-1] + arr[i] +1;str[i] = str[i+1];}printf("Array[2] = %d\n", arr[2]);printf("String = \"%s\"\n", str);return 0;}//Array[2] = 32 String = "At"
scanf and atoi
从标准输入读取的格式化输入(如键盘)
scanf(format-string, expr1, expr2, …);
将字符串转换为整数
int value = atoi(string);
eg
#include <stdio.h> // includes definition of BUFSIZ (usually =512) and scanf()
#include <stdlib.h> // includes definition of atoi()...char str[BUFSIZ];
int n;printf("Enter a string: ");
scanf("%s", str);
n = atoi(str);
printf("You entered: \"%s\". This converts to integer %d.\n", str, n);
result Enter a string: 9024 You entered: "9024". This converts to integer 9024.
Arrays and Functions
当数组作为参数传递给函数时,实际传递的是数组开头的地址
函数中数组的字符类型已知,大小未知
eg
int total, vec[20]; … total = sum(vec);
因为函数不知道数组有多大,所以可以将数组的大小作为一个额外参数传入,或者包含一个“终止值”来标记数组的结束。
eg
int total, vec[20]; … total = sum(vec,20);
Exercise #6 实现对数组中所有元素求和的函数,使用 int sum(int[],int)
int sum(int vec[], int dim)
{int i, total = 0;for(i=0;i<dim;i++){total += vec[i];}return total;
}
Multi-dimensional Arrays
q[0][1]==2.7
r[1][3]==8
q[1]=={3.1,0.1}
Defining New Data Types
typedef float Real;//定义新数据类名称
Real complex_calculation(Real a, Real b)
{Real c = log(a+b);...//based on exist datatypereturn c;
}
Structures
是一组变量的集合,可能是不同类型的
typedef struct {char name[30];int zID; } StudentT;
结构体可以嵌套在另一个结构体中
typedef struct {int day, month; } DateT;typedef struct {int hour, minute; } TimeT;typedef struct {char plate[7]; // e.g. "DSA42X"double speed;DateT d;TimeT t; } TicketT;
--------------------------------- | D | S | A | 4 | 2 | X | \0| | 7 bytes + 1 padding --------------------------------- | 68.4 | 8 bytes --------------------------------- | 2 | 6 | 8 bytes --------------------------------- | 20 | 45 | 8 bytes ---------------------------------
定义结构化数据类型本身不会分配任何内存
我们需要声明一个变量来分配内存
使用上述TicketT类型,我们声明并使用变量
#define NUM_TICKETS 1500typedef struct {…} TicketT;TicketT tickets[NUM_TICKETS]; // array of structs// Print all speeding tickets in a readable format
for (i = 0; i < NUM_TICKETS; i++) {printf("%s %6.2f %d/%d at %d:%d\n", tickets[i].plate,tickets[i].speed,tickets[i].d.day,tickets[i].d.month,tickets[i].t.hour,tickets[i].t.minute);
}// Sample output:
//
// DSA42X 68.40 2/6 at 20:45
%6.2f 6个字节来输出数字,取小数点后两位
结构体可以作为参数传递给函数:
void print_date(DateT d) {printf("%d/%d\n", d.day, d.month);
}int is_winter(DateT d) {return ( (d.month >= 6) && (d.month <= 8) );
}
Abstract Data Types 抽象数据类型
是一种信息隐藏方式
围绕数据建立分装
用户只能看到ADT的接口
ADT很重要,因为…
促进复杂程序的分解
使更改对客户端不可见
提高软件的可读性和结构化
允许在其他系统中重复使用模块
ADO=抽象数据对象
ADT=抽象数据类型
Stack 堆栈,LIFO 后进先出
创建空堆栈
把item插入(推)到堆栈上
删除(弹出)最近使用的item
检查堆栈是否为空
应用:在文本编辑器中撤消序列,括号匹配算法
eg
Stack Operation Return value
? create -
- isempty true
- push a -
a push b -
a b push c -
a b c pop c
a b isempty false
堆栈和队列(Stack vs Queue)
队列 FIFO 先进先出
Exercise #7- Stack&Queue
考虑前面的示例,但是使用队列而不是堆栈。 哪个元素会首先被取出(“出列”)
Stack as ADO
// Stack ADO header file#define MAXITEMS 10void StackInit(); // set up empty stack int StackIsEmpty(); // check whether stack is empty void StackPush(char); // insert char on top of stack char StackPop(); // remove char from top of stack
#include "Stack.h"
#include <assert.h>// define the Data Structure
typedef struct {char item[MAXITEMS];int top;
} stackRep;// define the Data Object
static stackRep stackObject;// set up empty stack
void StackInit() {stackObject.top = -1;
}// check whether stack is empty
int StackIsEmpty() {return (stackObject.top < 0);
}
// insert char on top of stack
void StackPush(char ch) {assert(stackObject.top < MAXITEMS-1);stackObject.top++;int i = stackObject.top;stackObject.item[i] = ch;
}// remove char from top of stack
char StackPop() {assert(stackObject.top > -1);int i = stackObject.top;char ch = stackObject.item[i];stackObject.top--;return ch;
}//assert(test) terminates program with error message if test fails
//static Type Var declares Var as local to Stack.c
Exercise#8 Bracket Matching
括号匹配…检查所有的开始括号,如“(”、“[”、“{”是否有匹配的结束括号“)”、“]”、“}”
(a+b) * c
a[i]+b[j]*c[k])
(a[i]+b[j])*c[k]
a(a+b]*c
void f(char a[], int n) {int i; for(i=0;i<n;i++) { a[i] = (a[i]*a[i])*(i+1); }}
a(a+b * c
bracketMatching(s): | Input stream s of characters | Output true if parentheses in s balanced, false otherwise | | for each ch in s do | | if ch = open bracket then | | push ch onto stack | | else if ch = closing bracket then | | | if stack is empty then | | | return false // opening bracket missing (case 1) | | | else | | | pop top of stack | | | if brackets do not match then | | | return false // wrong closing bracket (case 2) | | | end if | | | end if | | end if | end for | if stack is not empty then return false // some brackets unmatched (case 3) | else return true
Compilers 编译器
Summary
- Introduction to Algorithms and Data Structures
- C programming language, compiling with
gcc
- Basic data types (
char
,int
,float
) - Basic programming constructs (
if
…else
conditionals,while
loops,for
loops) - Basic data structures (atomic data types, arrays, structures)
- Basic data types (
- Introduction to ADTs
- Compilation
- Suggested reading (Moffat):
- introduction to C … Ch. 1; Ch. 2.1-2.3, 2.5-2.6;
- conditionals and loops … Ch. 3.1-3.3; Ch. 4.1-4.4
- arrays … Ch. 7.1, 7.5-7.6
- structures … Ch. 8.1
- Suggested reading (Sedgewick):
- introduction to ADTs … Ch. 4.1-4.3
21T2 9024-Week 01相关推荐
- 零起点学算法01——第一个程序Hello World!
零起点学算法01--第一个程序Hello World! Description 题目很简单 输出"Hello World!"(不含引号),并换行. Input 没有输入 Outpu ...
- hdu5296 01字典树
根据二进制建一棵01字典树,每个节点的答案等于左节点0的个数 * 右节点1的个数 * 2,遍历整棵树就能得到答案. AC代码: #include<cstdio> using namespa ...
- 20150411--Dede二次开发-01
20150411--Dede二次开发-01 目录 一.目前市场流行的电子商城系统 1 二.ecshop的介绍 1 三.安装 2 四.echsop 的目录结构 5 五.分析ecshop里面程序的架构 5 ...
- (九)单片机串行口 内部结构的讲解 01
1. 基本概念 常用于数据通信的传输方式有单工.半双工.全双工和多工方式. 单工方式:数据仅按一个固定方向传送.因而这种传输方式的用途有限,常用于串行口的打印数据传输与简单系统间的数据采集. 半双工方 ...
- Python 学习笔记01
print:直接输出 type,求类型 数据类型:字符串,整型,浮点型,Bool型 note01.py # python learning note 01 print('Hello world!') ...
- ACM1881 01背包问题应用
01背包问题动态规划应用 acm1881毕业bg 将必须离开的时间限制看作背包容量,先将他们由小到大排序,然后在排完序的数组中对每个实例都从它的时间限制开始(背包容量)到它的延长时间进行遍历: 1 # ...
- 什么是壳 - 脱壳篇01
什么是壳 - 脱壳篇01 让编程改变世界 Change the world by program 壳 在自然界中,植物用壳来保护种子,动物用壳来保护身体,我们人类没有壳,但我们有衣服,房子也起到了壳的 ...
- 端口01 - 零基础入门学习汇编语言67
第十四章:端口01 让编程改变世界 Change the world by program 引言 CPU可以直接读写3 个地方的数据 (1)CPU 内部的寄存器: (2)内存单元: (3)端口. 这一 ...
- 浅说——九讲背包之01背包
所谓九讲,也就是: 0/1背包 0/1背包降维 完全背包 多重背包(二进制优化) 混合背包 二维费用背包 分组背包 有依赖的背包 背包的方案总数\背包的具体方案路径 0/1背包: [问题描述](经典) ...
最新文章
- 世界上最遥远的距离是计算机不懂人类的时间
- CG CTF WEB bypass again
- 解决Error: undefined reference to `__android_log_print'
- ARM(IMX6U)裸机按键输入实验(BSP+SDK、GPIO输入与输出、按键消抖)
- 使用 Flomesh 强化 Spring Cloud 服务治理
- 数据库设计方法学概述
- sql语句,怎么取查询结果的位置
- 计算机专业是理科吗,计算机类和普通理科有什么区别?
- Linux操作系统原理与应用01:概述
- java的一些课程设计题目_Java课程设计
- mysql sin度数正玄值_正弦值角度对照表
- 完全停止Oracle中正在运行的JOB
- 【Python】python初学者应该知道与其他语言差异化的高效编程技巧(附测试代码+详细注释)
- USB-HDD和USB-ZIP制作U盘启动盘有什么区别?
- Altium Designer 在PCB中添加 图片 Logo 或者丝印
- 安全合规/GDPR--23--研究:GDPR风险评估与组织架构保障
- 在root目录下npm install报错Error: EACCES: permission denied, mkdir ‘/root/ttt/web/node_modul
- SIM900A、GPRS、GSM 基础知识
- java oj_用java怎么做oj啊
- Simulink嵌入式自动代码生成DSP 28335/28035/28x系列 (1)——官方例程(1)讲解 {ADC-PWM同步中断}