Programming and Coding
Download
Report
Transcript Programming and Coding
Introduction to Computer and Program Design
Lesson 1
Introduction
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
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
3
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
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++
6
Textbooks
C How to program, 6ed
By P.J. Deitel & H.M. Deitel
Publisher: Prentice Hall
Features:
Chapter 1: Introduction to computers
Plenty exercises
7
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
8
Textbooks
C++ Primer, 4ed
By Stanley B. Lippman,
Josée Lajoie, Barbara E. Moo
Publisher:
Addison Wesley
Features:
Introduction to OOP
中譯本:
侯捷 譯
碁峰 出版
9
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 的進階書
中譯本
蔡明志 譯
碁峰 出版
10
Reference Books
The C++ Standard Library - A Tutorial and Reference
By Nicolai M. Josuttis
Publisher: Addison-Wesley
Feature:
STL tool book
中譯本:
C++ 標準程式庫
侯捷,孟岩 譯
碁峰 出版
11
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/cppreferenc
ecom_feb09.zip
Google, Yahoo and programming forums (PTT/Programming)
12
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
Computer Organization
All computers consist of six components
14
Computer Organization
The motherboard of ?
圖片來源: Wikipedia
I/O: USB,Sound, …
Southbridge
= I/O controller
Memory
256 MB XDR
GPU(Graphics Processing Unit):
RSX 550MHz
CPU:
Cell Processor
PowerPC-base Core 3.2GHz
15
with Northbridge = Memory controller
Computer Organization
Desktop motherboard: ASUS P8P67
PCI slots
I/O: USB, Sound,
Network cable …
PCIe slots
Power socket
for CPU
CPU socket
Intel i7/i5
(LGA1155)
Memory socket
圖片來源: ASUS
SATA sockets
Power socket
16
Computer Organization
Memory access
Data bus
Memory
CPU
Address 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
17
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
Programming Flow
20
C++ IDE
Dev C++
http://www.bloodshed.net/devcpp.html
GCC-based compiler
GCC: GNU Compiler Collection
原始碼有開放下載(Open source), 不佔硬碟空間且免費
它的原始碼編輯器(editor)及 除錯器(debugger)有很多缺失
21
C++ IDE
Code::Blocks
http://www.codeblocks.org/
Multiple compiler support:
GCC (MingW / GNU GCC)
MSVC++
...and more
原始碼有開放下載(Open source), 不佔硬碟空間且免費
有出各種平台版本
除錯器(debugger)過於複雜難用
22
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: 免費精簡版,但已足夠開發一般的視窗程式
23
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~)
用來開發Windows 級MacOS X 的視窗程式
24
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
25
The History of the C Language
C language is created by Dennis Ritchie between 1969 -1972
1989, ANSI C89
ANSI: American National Standards Institute
1990, ISO C90 C89 C90 (C89 = C90)
1999, C99
2011, C11
C89 is the main development tool in the most embedded systems
ISO: International Organization for Standardization
Because C89 is simple, light weight, and high efficient
Dennis Ritchie 1941-2011
圖片來源: Wikipedia
26
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 程式
#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;
}
28
Programming and Coding
一段簡單的C 程式,加上註解
#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;
/* 告訴作業系統此程式將正常結束 */
}
29
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 常如此誤用:
#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;
}
31
Programming and Coding
更好用的 block comment
#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);
#endif
system("pause");
return 0;
}
32
Programming and Coding
The main function
所 C 程式的主要起始點
main function 是唯一的. 千萬不可寫兩個 main function在同一支程式 (即
使他們的return type 及and the arguments list 不相同)
Simple type of the main function:
int
int
main( void ) { // void means empty
main( ) {
…
…
}
}
Complete types of the main function:
int
main( int argc, char *argv[ ] )
{ … }
// For UNIX
33
Programming and Coding
變數 Variables
在記憶體佔有一席之地,用來存放資料以便進行各種運算。
變數使用前一定要被宣告: 告訴編譯器(compiler) 你要使甚麼樣的變數一即為這變
數取一個名字。
變數的宣告
Ex:
千萬不可以有兩個變數取相同名稱
int
x;
// Declare an integer
float y;
// Declare a 32-bit floatingpoint number
double z; // Declare a 64-bit floating-point number
unsigned integer i; // Declare an unsigned integer
char c;
// Declare a 8-bit character
char S[100];
// Declare a 100 characters text string
int
int
float
x;
x;
x;
// Declare an integer
// Error! Redeclaration of x!
// Error! Redeclaration of x!
34
Programming and Coding
變數的宣告
同時宣告多個同種類的變數 Multiple variables declaration:
int
float
a, b ,c;
// Declare three integers
x, y, z, w; // Declare four 32bit floating-point numbers
宣告同時初始化(initialization)
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
強烈建議所有變數在宣告同時也給初始值
35
Programming and Coding
Statements and Expressions
運算式 Expressions
一個運算式是由 變數(variables), 常數(constants), 運算子(operators)及 函數
呼叫 (function calls) 所組成
任何運算式皆會算出一個值 (value).
敘述 Statements
一句敘述是由符號 (tokens), 運算式(expressions), 及其他敘述句所組成.
以分號 (;)左為敘述句的結尾
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 */
36
Programming and Coding
左值(L-value)與右值(R-value)
非常重要的觀念!
左值L-value: 可以放在等號的左邊
一定是一個變數 因為變數在記憶體裡佔有一席之地
一定代表著可以寫入資料的記憶體空間
常數constant不可以當左值
右值R-value: 可以放在等號的右邊
任何可提供數值的符號(變數或常數)都可以當右值, 但是要注意左值與右值的
型態是否匹配
int x, y;
x = 1 + 2 * 3 / 4;
// x: L-value; 1+2*3/4: R-value
y = x;
// y: L-value; x: R-value
1+2*3/4 = y; // error! 1+2*3/4 cannot be a L-value
x+1 = y;
// error! x+1 cannot be a L-value
int *p;
// p 是一種專門存放某個 int變數的記憶體位址
// p 也是一種變數, 這種專門放位址的變數我們稱為指位器 (pointer)
p = x;
// error! p 與 x型態不匹配
37
C/C++ Operators - 1
Precedence
1(highest)
2
3
Operator
Description
::
++
-()
[]
.
->
typeid()
const_cast
dynamic_cast
reinterpret_cast
static_cast
++
-+
!
~
(type)
*
&
sizeof
new, new[]
Scope resolution (C++ only)
Suffix increment
Suffix decrement
Function call
Array subscripting
Element selection by reference
Element selection through pointer
Run-time type information (C++ only)
Type cast (C++ only)
Type cast (C++ only)
Type cast (C++ only)
Type cast (C++ only)
Prefix increment
Prefix decrement
Unary plus
Unary minus
Logical NOT
Bitwise NOT
Type cast
Indirection (dereference)
Address-of
Size-of
Dynamic memory allocation (C++ only)
delete, delete[]
Dynamic memory deallocation (C++ only)
(listed by Wikipedia)
Associativity
Left-to-right
Right-to-left
38
C/C++ Operators - 2
Precedence
4
5
6
7
8
9
10
11
12
13
14
Operator
Description
Associativity
.*
->*
*
/
%
+
<<
>>
<
<=
>
>=
==
!=
&
^
|
&&
||
Pointer to member (C++ only)
Pointer to member (C++ only)
Multiplication
Division
Modulo (remainder)
Addition
Subtraction
Bitwise left shift
Bitwise right shift
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to
Bitwise AND
Bitwise XOR (exclusive or)
Bitwise OR (inclusive or)
Logical AND
Logical OR
Left-to-right
(listed by Wikipedia)
39
C/C++ Operators - 3
Precedence
15
16
17
18
Operator
Description
?:
=
+=
-=
*=
/=
%=
<<=
>>=
&=
^=
|=
throw
,
Ternary conditional (see ?:)
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
Throw operator (exceptions throwing, C++ only)
Comma
Associativity
Right-to-left
Left-to-right
(listed by Wikipedia)
40
Programming and Coding
函數的規格 The specification of a function
Return_Type
Ex :
FunctionName(argument1, argument2, …. );
int getchar( void );
int printf( const char *format [, argument]... );
函數的呼叫 Function calling
Syntax:
Function_Name( )
Function_Name( argument1, argument2, …. )
int x = getchar();
// Call getchar without argument to obtain an input character
printf(“%d\n“, x);
// Call printf with two arguments to display the value of x
41
scanf & printf
scanf: 標準輸入函數; printf:標準輸出函數
使用前都要 #include <stdio.h>
第一個參數是必要的,而且是一個字串,代表輸入/出的格式
第二個之後的參數都是選項,代表輸入/出的資料
往後我們會再詳細的介紹這兩個function
example:
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
42
條件敘述 Condition Statements
if then else
int x = 10;
if(x == 1)
printf("x is 1\n");
else
printf("x is not 1\n");
// this line will be executed
if(x = 1)
printf("x is 1\n"); // this line will be executed, why?
else
printf("x is not 1\n");
Be careful for the declaration statements in block
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);
43
條件敘述 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?
44
條件敘述 Condition Statements
if … then … else …
if(…){
…
}
else{
if(…){
…
}
else{
…
}
}
if(…){
…
}
else if(…){
…
}
else{
…
}
if(…){
…
}
else if(…){
…
}
else{
…
}
else{
// Error!
…
}
45
重複性敘述 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
46
重複性敘述 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);
47
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
48
Compiler’s Warnings & Errors
錯誤訊息 error messages
錯誤訊息會中斷編譯工作.
錯誤訊息你必須去解決它.
x = 1 + 1 // syntax error : missing ';‘
if( x<0){
x = 100;
// fatal error : without right brace ‘}'
49
Bugs
What is a bug?
就是程式上的執行錯誤及瑕疵
早期的計算機由於體積非常龐大,有些小蟲子可能會鑽入機器內部,造
成計算機工作失靈。因此用「Bug」來稱之。
例如:
文法上錯誤 Lexical error
連結失敗Linking failed
使用到位初始化的變數 Uninitiated variable
除以零 Divided by zero
使用作業系統的資源造成的錯誤 System error
邏輯上的錯誤 Logical error
50
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)。
本題禁止用字串處理方式,輸入數字部分只能用 scanf("%d", &n);。
例:輸入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