lesson 1 introduction
DESCRIPTION
Lesson 1 Introduction. James C.C. Cheng Department of Computer Science National Chiao Tung University. Introduction to Computer and Program Design. About Me. 鄭昌杰 Cheng, Chang-Chieh Ph.D. Candidate, department of Computer Science, NCTU Email: [email protected] Office: - PowerPoint PPT PresentationTRANSCRIPT
Lesson 1
Introduction
Introduction to Computer and Program Design
James C.C. Cheng
Department of Computer Science
National Chiao Tung University
About Me 鄭昌杰 Cheng, Chang-Chieh
Ph.D. Candidate, department of Computer Science, NCTU Email:
[email protected] Office:
交通大學新竹光復校區電資大樓 704 室 (Room 704, MISRC, NCTU)
Tel: 03-5712121 # 59268
2
3
Syllabus
Introduction
C language overview
Data Types and Variables
Operators and Expressions
Statements
Pointers, Arrays and Memory Management
Functions
Standard I/O
String processing
Custom data type
Scoring
期中考 ( 筆試 ) 25%
期末考 ( 筆試 ) 25%
上機考 25%
平時作業 ( 含上課狀況 ) 25%
4
Why should I take this course?
Every thing is computer
To learn the programming technique, because you can design a valuable and interesting computer program
the number of experiment results could be very large.
you have to control the instruments by computer
5
6
Why should I learn the C and C++
For basic computer concepts learning
To design a high performance program
Windows programming GUI (graphical user interface) application software
Mobile software development iPhone, iPad iOS applications (apps)
Xcode with C++ or Objective C
Android applications GUI JAVA
Kernel C++
7
Textbooks
C How to program, 6ed By P.J. Deitel & H.M. Deitel
Publisher: Prentice Hall
Features: Chapter 1: Introduction to computers
Plenty exercises
8
Textbooks
The C programming Language, 2ed Authors: Brian W. Kernighan and Dennis M. Ritchie
Publisher: Prentice Hall
Features: Introduction to the C language
The first book on C language
Authors are the creators of C
9
Textbooks
C++ Primer, 4ed By Stanley B. Lippman,
Josée Lajoie, Barbara E. Moo
Publisher:
Addison Wesley
Features: Introduction to OOP
中譯本 : 侯捷 譯 碁峰 出版
10
Reference Books
Thinking in C++ Volume 1 & Volume 2 , 2ed by Bruce Eckel, Chuck Allison
Free Electronic Book, http://www.mindviewinc.com/Index.php
Features: C++ and OOP 的進階書
中譯本 蔡明志 譯 碁峰 出版
11
Reference Books
The C++ Standard Library - A Tutorial and Reference By Nicolai M. Josuttis
Publisher: Addison-Wesley
Feature: STL tool book
中譯本 : C++ 標準程式庫 侯捷,孟岩 譯 碁峰 出版
12
Internet Resources
MSDN, Microsoft Developer Network http://msdn.microsoft.com/
Cplusplus.com http://www.cplusplus.com/
C++ wiki Link:
http://www.cppreference.com/wiki/ chm version:
http://www.cppreference.com/wiki/_media/about/
cppreferencecom_feb09.zip
Google, Yahoo and programming forums (PTT/Programming)
What is a computer?
A machine designed to solve some problem.
A programmable machine It can execute a sequence of instructions
Mostly, it is a digital system 二進位系統 ( binary system):
0/1, true/false, turn on/turn off.
It has data storage devices 非揮發性資料儲存裝置 Non-volatile data storage devices :
Punched cards, magnetic tapes, magnetic disks, optical disk, ROM
揮發性資料儲存裝置 Volatile data storage devices: Transistors, registers, memory, RAM, SDRAM, DDR
A communication device I/O ports, RS-232, LPT, IDE, SATA, USB
Ethernet, Internet
13
14
Computer Organization
All computers consist of six components
15
Computer Organization The motherboard of ?
Memory256 MB XDR
CPU:Cell Processor PowerPC-base Core 3.2GHz with Northbridge = Memory controller
GPU(Graphics Processing Unit):RSX 550MHz
I/O: USB,Sound, …
Southbridge = I/O controller
圖片來源 : Wikipedia
Computer Organization Desktop motherboard: ASUS P8P67
16
I/O: USB, Sound, Network cable …
CPU socketIntel i7/i5 (LGA1155)
Memory socket
Power socketSATA sockets
PCI slots PCIe slots
Power socket for CPU
圖片來源 : ASUS
17
Computer Organization
Memory access
CPUMemory
Address bus
Data bus
Bus: A bundle of electronic signal wires. In 32-bit computer, the bus consists of 32 wires In 64-bit computer, the bus consists of 64 wires
Quiz
找一台桌上型電腦 (desktop), 你能說出每一個開關、燈號、插孔及各裝置的名稱 ( 中英文 ) 及用途嗎 ?
18
What is programming? 設計一連串的命令與符號讓電腦去解決某些問題
所設計的一連串命令與符號稱為原始碼 (Source code)
Machine code 機器碼 以 0 及 1 兩種符號所構成的數碼 原始碼必須被翻譯 (compile) 成機器碼才可讓電腦執行 Program language 程式語言 設計原始碼所必須遵守的規則及 語法 較著名的程式語言 ( 從低階 ( low-level) 到高階 ( high-level)):
Assembly
C
C++
JAVA
Delphi (Pascal)
Microsoft Basic
SQL
19
20
Programming Flow
21
C++ IDE
Dev C++ http://www.bloodshed.net/devcpp.html
GCC-based compiler GCC: GNU Compiler Collection
原始碼有開放下載 (Open source), 不佔硬碟空間且免費 它的原始碼編輯器 (editor) 及 除錯器 (debugger) 有很多缺失
22
C++ IDE
Code::Blocks http://www.codeblocks.org/
Multiple compiler support: GCC (MingW / GNU GCC)
MSVC++
...and more
原始碼有開放下載 (Open source), 不佔硬碟空間且免費 有出各種平台版本 除錯器 (debugger) 過於複雜難用
23
C++ IDE
Visual Studio 不只有 C++ 還包含了 Visual Basic, C# and J#.
它的 C++ compiler 是微軟自己發明的 MS C++
在 v6.0 之前 , VS 使用 MFC (Microsoft Foundation Classes) 來建立視窗用程式 .
MFC: 問題缺失非常多的一個函式庫 !
VS 7.0~ use the .NET Framework.
Visual Studio Express: 免費精簡版,但已足夠開發一般的視窗程式
24
C++ IDE
Embarcadero C++ Builder XE2 (2011) Based on Turbo C++ (1991~2006)
History Borland C++ Builder (1997~2006)
CodeGear C++ Builder (2006~2008)
Embarcadero C++ Builder (2008~)
用來開發W indows 級 MacOS X 的視窗程式
25
C++ IDE
QT http://qt.nokia.com/products/
Based on MinGW (Minimalist GNU for Windows)
在歐洲及中國大陸非常流行 免費 用來開發各種平台的視窗程式 (source code cross-platform)
Microsoft Windows
X-Windows
Mac OS
iOS
Android
The History of the C Language
C language is created by Dennis Ritchie between 1969 -1972 1989, ANSI C89
1990, ISO C90 C89 C90 (C89 = C90)
1999, C99
2011, C11
C89 is the main development tool in the most embedded systems
Because C89 is simple, light weight, and high efficient
26
ANSI: American National Standards Institute
ISO: International Organization for Standardization
Dennis Ritchie 1941-2011
圖片來源 : Wikipedia
The History of the C++ Language
1979, Bjarne Stroustrup develops the “C with Classes” language C language with object-oriented programming
1983, the “C with Classes” the C++ language
1998, 1st standard version: C++98
2003, 2nd standard version: C++03
2011, 3rd standard version: C++11
27
Programming and Coding 一段簡單的 C 程式
28
#include <stdlib.h> #include <stdio.h> int main(){ int x = 0; scanf("%d", &x); x = 1 + 2 * 3 / 4; printf ("%d\n", x); system("pause"); return 0;}
Programming and Coding 一段簡單的 C 程式,加上註解
29
#include <stdlib.h> // 將 stdlib.h 裡面的內容複製貼上在這裡#include <stdio.h> // 將 stdin.h 裡面的內容複製貼上在這裡/* C89-style 區塊註解 . 請少用 C89 區塊註解 ! Why? */int main() /* 函數宣告式 :
return_type function_name ( arguments_list ) */{ //main 函數從這左大括號開始 int x = 0; // 變數宣告式 scanf("%d", &x); // scanf: 將資料從至標準輸入裝置 (standard input device) 讀取出來的函數 x = 1 + 2 * 3 / 4; // 將 1 + 2 * 3 / 4 的結果寫到 x 裡 printf ("%d\n", x); // printf: 將資料輸出至標準輸出裝置 (standard output device) 的函數 system("pause"); // 暫停指令,注意 ! 只有微軟的環境下才能使用 return 0; /* 告訴作業系統此程式將正常結束 */}
Programming and Coding
#include directive( 指令 ) 將所指定的檔案內容複製貼上 #include <SourceFile>
The path of SourceFile is
Default_Include_Path/SourceFile
The setting of Default_Include_Path
Tools / Compiler Options / Directories / C includes
#include “SourceFile“ Compiler searches the SourceFile if it is an absolute path
Compiler searches the SourceFile in the current directory if SourceFile is just
a filename
30
Programming and Coding
Comments Single line comment //
c89 block comment /* */
c89 block comment 常如此誤用 :
31
#include <stdlib.h>#include <stdio.h> int main(){
/* int x; /* x = 1 + 2 * 3 / 4; printf ("%d\n", x); */ printf ("Bye!\n", x);*/ system("pause"); return 0;
}
Programming and Coding
更好用的 block comment
32
#include <stdlib.h>#include <stdio.h> int main() {
#if 0 int x; #if 0 x = 1 + 2 * 3 / 4; printf ("%d\n", x); #endif printf ("Bye!\n", x); #endifsystem("pause"); return 0;
}
Programming and Coding
The main function 所 C 程式的主要起始點 main function 是唯一的 . 千萬不可寫兩個 main function 在同一支程式 (
即使他們的 return type 及 and the arguments list 不相同 )
Simple type of the main function:
Complete types of the main function:
33
int main( ) {
…}
int main( void ) { // void means empty …
}
int main( int argc, char *argv[ ] ) { … } // For UNIX
Programming and Coding 變數 Variables
在記憶體佔有一席之地,用來存放資料以便進行各種運算。 變數使用前一定要被宣告 : 告訴編譯器 (compiler) 你要使甚麼樣的變數一即為這
變數取一個名字。
變數的宣告 Ex:
千萬不可以有兩個變數取相同名稱
34
int x; // Declare an integerfloat y; // Declare a 32-bit floating-point numberdouble z; // Declare a 64-bit floating-point numberunsigned integer i; // Declare an unsigned integerchar c; // Declare a 8-bit characterchar S[100]; // Declare a 100 characters text string
int x; // Declare an integerint x; // Error! Redeclaration of x!float x; // Error! Redeclaration of x!
Programming and Coding
變數的宣告 同時宣告多個同種類的變數 Multiple variables declaration:
宣告同時初始化 (initialization)
強烈建議所有變數在宣告同時也給初始值
35
int a, b ,c; // Declare three integersfloat x, y, z, w; // Declare four 32bit floating-point numbers
int a = 0, b = 1, c;// a = 0 and b = 1 but c = ?
float x = 1.2f, y, z, w = 1.0f;// x = 1.2 and w = 1.0 but y and z = ?// 1.2f means 1.2 is a 32-bit floating-point number// 1.2 means 1.2 is a 64-bit floating-point number
Char S[100] = {0}; // All characters are zero
Programming and Coding
Statements and Expressions 運算式 Expressions
一個運算式是由 變數 (variables), 常數 (constants), 運算子 (operators) 及 函數呼叫 (function calls) 所組成
任何運算式皆會算出一個值 (value).
敘述 Statements 一句敘述是由符號 (tokens), 運算式 (expressions), 及其他敘述句所組成 .
以分號 (;) 左為敘述句的結尾
36
int x; // A declaration statement
x = 1 + 2 * 3 / 4; /* An assignment statement 1+2*3/ 4 is an expression */
x = printf("Hello\n"); /*An assignment statement printf("Hello\n"); is an expression */
Programming and Coding
左值 (L-value) 與右值 (R-value) 非常重要的觀念 ! 左值 L-value: 可以放在等號的左邊
一定是一個變數 因為變數在記憶體裡佔有一席之地 一定代表著可以寫入資料的記憶體空間 常數 constant 不可以當左值
右值 R-value: 可以放在等號的右邊 任何可提供數值的符號 ( 變數或常數 )都可以當右值 , 但是要注意左值與右值
的型態是否匹配
37
int x, y;x = 1 + 2 * 3 / 4; // x: L-value; 1+2*3/4: R-valuey = x; // y: L-value; x: R-value 1+2*3/4 = y; // error! 1+2*3/4 cannot be a L-valuex+1 = y; // error! x+1 cannot be a L-valueint *p; // p 是一種專門存放某個 int 變數的記憶體位址
// p 也是一種變數 , 這種專門放位址的變數我們稱為指位器 (pointer)p = x; // error! p 與 x型態不匹配
C/C++ Operators - 1
38
Precedence Operator Description Associativity
1(highest) :: Scope resolution (C++ only) Left-to-right
2
++ Suffix increment-- Suffix decrement() Function call[] Array subscripting. Element selection by reference-> Element selection through pointertypeid() Run-time type information (C++ only) const_cast Type cast (C++ only) dynamic_cast Type cast (C++ only)reinterpret_cast Type cast (C++ only)static_cast Type cast (C++ only)
3
++ Prefix increment Right-to-left-- Prefix decrement+ Unary plus- Unary minus! Logical NOT~ Bitwise NOT(type) Type cast* Indirection (dereference)& Address-ofsizeof Size-ofnew, new[] Dynamic memory allocation (C++ only)
delete, delete[] Dynamic memory deallocation (C++ only)
(listed by Wikipedia)
C/C++ Operators - 2
39
Precedence Operator Description Associativity
4.* Pointer to member (C++ only) Left-to-right->* Pointer to member (C++ only)
5* Multiplication/ Division% Modulo (remainder)
6+ Addition- Subtraction
7<< Bitwise left shift>> Bitwise right shift
8
< Less than<= Less than or equal to> Greater than>= Greater than or equal to
9== Equal to!= Not equal to
10 & Bitwise AND11 ^ Bitwise XOR (exclusive or)12 | Bitwise OR (inclusive or)13 && Logical AND14 || Logical OR
(listed by Wikipedia)
Precedence Operator Description Associativity
15 ?: Ternary conditional (see ?:) Right-to-left
16
= Direct assignment
+= Assignment by sum
-= Assignment by difference
*= Assignment by product
/= Assignment by quotient
%= Assignment by remainder
<<= Assignment by bitwise left shift
>>= Assignment by bitwise right shift
&= Assignment by bitwise AND
^= Assignment by bitwise XOR
|= Assignment by bitwise OR
17 throw Throw operator (exceptions throwing, C++ only) 18 , Comma Left-to-right
40
C/C++ Operators - 3
(listed by Wikipedia)
Programming and Coding
函數的規格 The specification of a function Return_Type FunctionName(argument1, argument2, …. );
Ex : int getchar( void );
int printf( const char *format [, argument]... );
函數的呼叫 Function calling Syntax:
Function_Name( )
Function_Name( argument1, argument2, …. )
41
int x = getchar(); // Call getchar without argument to obtain an input characterprintf(“%d\n“, x); // Call printf with two arguments to display the value of x
scanf & printf
scanf: 標準輸入函數 ; printf: 標準輸出函數 使用前都要 #include <stdio.h>
第一個參數是必要的,而且是一個字串,代表輸入 / 出的格式 第二個之後的參數都是選項,代表輸入 / 出的資料 往後我們會再詳細的介紹這兩個 function
example:
42
int x = 0, y = 0, z = 0;scanf("%d", &x);scanf("%d %d", &y, &z);printf("%d, %d, %d\n", x, y, z);
scanf("%d%d%d", &x, &y, &z);printf("%d", x);printf("%d\t\n%d\n", y, z);
%d: 依照順序抓後面的參數,並以十進位整數來處理
& 變數名稱 : 取出變數在記憶體的位址
\n: new line 換行\t: tab
43
條件敘述 Condition Statements
if then else
Be careful for the declaration statements in block
int x = 10;if(x == 1) printf("x is 1\n");else printf("x is not 1\n");
// this line will be executedif(x = 1) printf("x is 1\n"); // this line will be executed, why?else printf("x is not 1\n");
int n;scanf("%d", &n); if(n >= 0){ int n = n; // An undefined behavior printf("%d is positive\n", n); }else printf("%d is negative\n", n);
44
條件敘述 Condition Statements
if … then … else … Do not write such condition expression
if( 0<= x < 10 ) if( (0<=x) && (x < 10) )
It will always be true. Why?
45
條件敘述 Condition Statements
if … then … else …
if(…){
…
}
else{
if(…){
…
}
else{
…
}
}
if(…){
…
}
else if(…){
…
}
else{
…
}
if(…){
…
}
else if(…){
…
}else{ …}
else{ // Error!
…
}
46
重複性敘述 Iteration Statements
重複性敘述代表這種敘述句會重複執行數次 C++ 有三種重複性敘述
while (expression){ … } do { … } while (expression); for (s-expression; expression; n-expression) { … }
迴圈結束條件 loop-termination criteria The r-value of expression is false break
continue The continue statement ignore the rest statements and passes control
to the next iteration
47
重複性敘述 Iteration Statements
Compare these three cases:
int n = 0, s = 0;scanf("%d", &n);while(n!=0){ s = s + n; n = n – 1;}printf("%d\n", s);
int n = 0, s = 0;scanf("%d", &n);do{ s = s + n; n = n – 1;} while(n != 0);printf("%d\n", s);
int n = 0, s = 0;int i = 0;scanf("%d", &n);for(i=1; i<=n; ++i) s = s + i;printf("%d\n", s);
48
Compiler’s Warnings & Errors
警告訊息 Warning messages Warning 不會中斷編譯工作 .
Warning 可以被忽略 .
int x = 1.0; warning C4244: '=' : conversion from 'double' to 'int',
但是有些 Warning 不可以被忽略int x = -1;
unsigned int y = 0;
if( x > y) printf("%d > %d", x, y);
warning C4018: '>' : signed/unsigned mismatch
49
Compiler’s Warnings & Errors
錯誤訊息 error messages 錯誤訊息會中斷編譯工作 .
錯誤訊息你必須去解決它 . x = 1 + 1 // syntax error : missing ';‘
if( x<0){
x = 100;
// fatal error : without right brace ‘}'
50
Bugs
What is a bug? 就是程式上的執行錯誤及瑕疵 早期的計算機由於體積非常龐大,有些小蟲子可能會鑽入機器內部,造
成計算機工作失靈。因此用「 Bug」來稱之。 例如 :
文法上錯誤 Lexical error
連結失敗 Linking failed
使用到位初始化的變數 Uninitiated variable
除以零 Divided by zero
使用作業系統的資源造成的錯誤 System error
邏輯上的錯誤 Logical error
Debugging in Dev C++ Breakpoint
An stopping or pausing place in a program
Set a breakpoint in Dev C++
Press Ctrl + F5 or by clicking in front of the line, outside of the editor window
Debug mode Debug / Debug or press F8
Start to run your program
Stop on the first breakpoint line. Notice that the breakpoint line not be executed
yet.
Continue to the next line:
Debug / Next Step or press F7
Continue to the next breakpoint
Debug / Continue or press Ctrl + F7
Stop the execution:
Debug / Stop Execution or press Ctrl + Alt + F2
The code must be recompiled if the code has been modified
51
Debugging in Dev C++ How to monitor the variables?
Put the mouse icon on the variable for a while
Or mark the variable, right click on it and click the Add Watch
Or press F4 then type the name of the variable
The value of the variable will be shown on the debug window, the left
side of the code editor.
52
練習題1. 台灣有四種硬幣: 1元、 5元、 10元、 50元。請寫一個程式,讓使用者可以輸入一個正整數,並算出最佳的硬幣組合。 例:輸入 136 ,則會算出 1 個 1元、 1 個 5元、 3 個 10元、 2 個 50元
2. 請寫一個程式,讓使用者可以輸入一個十進位正整數, 並加總所有位數 (digit)。 1. 本題禁止用字串處理方式,輸入數字部分只能用 scanf("%d", &n);。2. 例 : 輸入 8051 ,則會顯示 8+0+5+1 = 14
3. 費伯納西數列 (Fibonacci number) F0 = 1, F1 = 1
Fn = Fn-1 + Fn-2 if n > 1
請寫一個程式,讓使用者可以輸入一個正整數 n。再個別以while , do…while ,及 for loop 這三種重複性敘述來產生 F0~Fn 的費伯納西數
例 : 輸入 12 ,則會顯示三次下列結果 ( 用三種不同的重複性敘述 )
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
53