目录
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) { declarations statements return …; }
如果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 \0
int 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 datatype
return 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 1500
typedef 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 10 void 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