C/C++ Basics (I) Variables, Expressions and Assignme nts Berlin Chen 2003 ok: Walter Savitch, "Absolute C++," Addison Wesley, 2002
C/C++ Basics (I)
Variables, Expressions and Assignments
Berlin Chen 2003
Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002
2
Introduction to C++
• Programming Languages– Low-level languages
• Machine, assembly– High-level languages
• B, C, C++, ADA, COBOL, FORTRAN– Object-Oriented-Programming in C++
• C++ Terminology– Programs and functions– Basic Input/Output (I/O) with cin and cout
3
Introduction to C++
• C++ is thought of C with classes (and othermodern features added), is a high level language
• C is first developed by Dennis Ritchie of AT&T in the 1970s for the UNIX system
• Bjarne Stroustrup of AT&T developed C++ in the early 1980s
• Most C is a subset of C++, and so most C programs are also C++ programs (The reverse is not true!)
4
C++ and Object-oriented Programming (OOP)
• The main characteristics of OOP– Encapsulation ( 資料封裝 )
• A form of information hiding and abstraction
– Inheritance ( 繼承 )• Has to do with writing reusable code
– Polymorphism ( 多形 )• Refers to a way that a single name can have multiple meanin
gs in the context of inheritance
– OOP provides classes, a kind of data type combining both data and algorithms( 演算法 )
– C++ tempers its OOP features
5
Outline• Basic Characteristics• Identifiers
– Keywords or Reserved Words– Variables
• Data types– Assigning Data for Variables
• Literal Data or Constants • Console Input/Output• Escape Sequences• Arithmetic Operators• Type Casting
6
Basic Characteristics of C/C++…void main(void){ cout << “Hello World ! \n”; …}
0010000001101010
…..
01101010
C/C++ Language(Text Files)
xxx.cpp
Compiler 編譯器VC++, gcc
Machine Language(Binary Files)
High level language-readable-machine independent (portable)
Low level language-unreadable-machine dependent
7
Basic Characteristics of C/C++
• C/C++ is case-sensitive ( 注意大小寫 )
• A program composed of one to several functions ( 函數 )– 每個 C/C++ 都需有一個稱為 main() 的函數
int main(void){ statement_1; statement_2; …
statement_n; return 0; // 結束函數}
函數標題
函數主體
函數定義
函數名稱
結束函數註解 (comment) 以“ //” 為起始
敘述 (statement) 以分號結束
8
Basic Characteristics of C/C++
• Program Style - Readability– 儘可能每行寫一個敘述 (statement)– 函數開始與結束之左右大括號各佔一行– 函數主體之敘述從大括號處往內 ( 右 ) 縮– 函數名稱與之後的左右括號不需要有空白
9
An example of C++ program#include <iostream>
using namespace std;
void main (void)
{
const double RATE=6.9;
double deposit;
cout << "Enter the amount of your deposit $";
cin >> deposit;
double newBalance;
newBalance= deposit+ deposit*(RATE/100.0);
cout << "In one year, the deposit will grow to\n" <<"$"<< newBalance;
}
Enter the amount of your deposit $ 100In one year, the deposit will grow to$106.9
輸入
C++ 程式
程式執行過程
標頭檔名及名稱空間
10
Identifiers ( 識別字 )• Identifiers are items defined/used in a program
– Keywords ( 關鍵字 )or Reserved Words ( 保留字 )– Variables ( 變數 ) 、 function names ( 函數名稱 ) 、 la
bels (標記)
• Identifiers must start with either a letter (A-Z, a-z) or the under score symbol(_), and the remaining characters must be letters (A-Z, a-z), digits(0-9), or the underscore symbol(_)
• Identifiers are case sensitive and have no limit to their length ( 大小寫有別、長度不受限 )
11
Identifiers• Valid ( 合法的 ) Identifiers: x, x1, x_1, ABC123z
7,…
• Invalid ( 不合法的 ) Identifiers: 12, 3x, %change, data-1, myfirst.c
• Identifier started with underscore are informally reserved for system (should avoid using it)– 以底線為首的命名方式通常保留給系統使用,因此我們在變數、函
數等命名時儘量不要使用
• Identifier are usually spelled with their first letter in lowercase
• topSpeed, bankRate1, bankRate2, timeOfArrival, …儘量使用有意義的名稱
12
Keywords or Reserved Words
• A special class of identifiers which have predefined meaning in C/C++ and cannot be used as names for variables or anything else– 關鍵字或保留字是 C/C++ Compiler 本身所使用的– 如 : break case char float
do goto long double if else .. … ….
– 我們只能使用它們,不能重新定義它們
• Some predefined words, such as cin and cout are not keywords, because they are not the core of C/C++ language
在某些編輯環境下保留字會以特別的顏色顯示
13
Variables
• A memory location to store data for a program
• Must declare all data (variables) before use in program– Tell the compiler/computer what kind of data you will
be storing in variables int numberOfBeans; double oneWeight, totalWeight;
• Variables can be declared any place– Declared either just before they are used or at the sta
rt of a block “{” (or a function/procedure)– 通常在程式或每個函式開頭宣告,也可以在程式任意
位置用到時才宣告
14
Variables
599
399.14
1000 numberOfBeans
1004
2108
2112
oneWeight
Memory
15
Variables
• Declaring ( 宣告 ) and Defining ( 定義 )– Declaring: the name of a variable is introduced
int numberOfBeans; // 整數宣告 char nKey; // 字元宣告
– Defining: the storage for the named variable is allocated
numberOfBeans=10000;
nKey=‘A’;
• A variable declaration both declares and defines the variable
int numberOfBeans=10000;
char nKey=‘A’;
16
Basic Data Types
TYPE NAME
MEMORY
USED
SIZE RANGE PRECISION
short 2 bytes -32768 ~ +32767 -
int 4 bytes -2,147,483,648 ~ +2,147,483,647
-
float 4bytes ±10-38 ~ ± 1038 7digits
double 8 bytes ± 10-308 ~ ± 10308 15digits
char 1byte All ASCII characters
-
bool 1 byte true, false -
整數型態
浮點數型態
字元或字串型態
布林數型態
有效位數及指數範圍不同
17
Assigning Data for Variables • Initializing data in declaration statement
int myValue = 0; or int myValue(0);
• Assigning data during execution myValue = 0;
– Lvalues (left-side) & Rvalues (right-side)– Lvalues must be variables, Rvalues can be a
ny expression ( 運算式 )– Example:
distance = rate * time;Lvalue: ‘distance’ , Rvalue: ‘rate * time’
18
Assigning Data for Variables
• Assigning data during execution (cont.)
– 將等號 (=) 右邊的運算式的值指定給左邊的變數
VarName= Expression; ( 變數=運算式 ;) 敘述 (a statement)
19
Assigning Data for Variables
• Compatibility of data assignments– Type mismatches– General Rule: Cannot place value of one typ
e into variable of another type
e.g.:
int intVar;
…
intVar = 2.99; // 2 is assigned to intVar!• Only integer part ‘fits’, so that’s all that goes• Called ‘implicit’ or ‘automatic type conversion’
20
Assigning Data for Variables• Example: char( 字元 ) vs. short ( 整數 )
#include <iostream>using namespace std;void main() //Relation Between char and short{ char testChar='X'; short testShort=testChar;
cout << "The ASCII for "<<testChar<<" is "<<testShort<<"\n"; testChar=testChar+1; testShort=testChar; cout << "The ASCII for "<<testChar<<" is "<<testShort<<"\n"; testChar=122; cout << "New testChar is "<<testChar<<"\n";}
21
Assigning Data for Variables
• bool – C++ assigns nonzero values to true and zero
value to false bool start= true;
bool start= false;
bool start= 100 ; //start assigned true
bool start= 0 ; //start assigned false
int ans = true ; //start assigned 1
int ans = false; //start assigned 0
22
Literal Data or Constants ( 常數 )
• Cannot change values during execution Examples:
2 // Literal constant int 整數575.34 // Literal constant double 浮點數5.7534e2 // Literal constant double 浮點數3.4e-2 // Literal constant double (0.034)‘Z’ // Literal constant char 字
元“Hello World” // Literal constant string 字串
• Called ‘literals’ ( 實字 ) because you ‘literally typed’ them in your program!
23
Literal Data or Constants ( 常數 )• Naming of constants
– Literal constants provide little meaning e.g.: seeing 24 in a program, tells nothing about
what it represents– Use named constants instead
• Meaningful name to represent data const double = 6.9;– Called a ‘declared constant’ or ‘named
constant’
• Now use it’s name wherever needed in program – Added benefit: changes to value result in one fix
若程式中數個地方用到同一個常數,要修改其值,只要修改符號定義一處即可
24
An example of C++ program#include <iostream>
using namespace std;
void main (void)
{
constant double RATE=6.9;
double deposit;
cout << "Enter the amount of your deposit $";
cin >> deposit;
double newBalance;
newBalance= deposit+ deposit*(RATE/100.0);
cout << "In one year, the deposit will grow to\n" <<"$"<< newBalance;
}
Enter the amount of your deposit $ 100In one year, the deposit will grow to$106.9
輸入
C++ 程式
程式執行過程
25
Escape Sequences ( 逸出順序、控制碼 )
• Backslash,( 背斜線 ) \ preceding a character ( 字元 )
• Instructs compiler: a special ‘escapecharacter’ ( 逸出字元 ) is coming– 逸出字元 : 字串及字元中無法顯示之字元
ESCAPE SEQUENCES MEANING
\n 換行 / 新列 (New line)
\' 單引號 (single quote)
\" 雙引號 (double quote)
\a 響鈴 (bell)
26
Escape Sequences
#include <iostream>using namespace std;
void main() //escape sequence{ cout <<'\a'<<"This is a test for escape sequences\n"; cout <<"How about you \"computer course\"?\n";}
27
Arithmetic Operators ( 算數運算子 )
Arithmetic Operators MEANING
+ 相加 - 相減* 相乘/ 相除% 餘數 ( 模數 )
使用模數運算子時,必須兩個運算元都是整數才行
• 5 arithmetic operators
• Precedence ( 優先權 ) rules – standard rules如 *,/,% 優先於 +,- ; 由左至右之結合律 (associative)
float logs=120/4*5; //150 ? 6?
28
Arithmetic Operators ( 算數運算子 )#include <iostream>using namespace std;
void main(){ int numA, numB, finalResult;
cout << " 請輸入第一個整數 : "; cin >> numA; cout << " 請輸入第二個整數 : "; cin >> numB;
finalResult=numA+numB; cout << " 相加的結果 : " <<"$"<< finalResult<<"\n";
finalResult=numA-numB; cout << " 相減的結果 : " <<"$"<< finalResult<<"\n"; finalResult=numA*numB; cout <<" 相乘的結果 : " <<"$"<< finalResult<<"\n"; finalResult=numA/numB; cout <<" 相除的結果 : " <<"$"<< finalResult<<"\n"; finalResult=numA%numB; cout <<" 相除的餘數 : " <<"$"<< finalResult<<"\n";}
29
Arithmetic Precision ( 算數運算精確度 )
• ‘Highest-order operand’ determines typeof arithmetic ‘precision’ performed
– Common pitfall!
• Examples:– 17 / 5 evaluates to 3 in C++! (Both operands are integers)
• Integer division is performed!
– 17.0 / 5 equals 3.4 in C++!• Highest-order operand is ‘double type’• Double ‘precision’ division is performed!
– int intVar1 =1, intVar2=2; intVar1 / intVar2 equals 0 in C++!
• Performs integer division!
30
Arithmetic Precision
• Calculations done ‘one-by-one’– 1 / 2 / 4.0 / 8 performs 3 separate divisions
• First 1 / 2 equals 0• Then 0 / 4.0 equals 0.0• Then 0.0 / 8 equals 0.0!
– What if 1 / 4.0/ 2 / 8 ?
31
Type Casting ( 型態轉換 )
• Implicit – also called ‘Automatic’– Done for you by C++ automatically
17 / 5.5 ‘implicit type cast’ to take place, casting the 17 17.0
• Explicit type conversion– Programmer specifies conversion with cast operator
(double)17 / 5.5; or double(17 )/ 5.5;
(double) myInt / myDouble;
old C syntax old C++ syntax
32
Shorthand Operators
• Increment (++)& Decrement (--) Operators– Just short-hand notation
• Increment operator,++ intVar++; is equivalent to
intVar = intVar + 1;
• Decrement operator, -- intVar--; is equivalent to
intVar = intVar – 1;
33
Shorthand Operators Post-Increment in Action
• Post-Increment in Expressions: int n = 2, valueProduced;
valueProduced = 2 * (n++); cout << valueProduced << "\n"; cout << n << "\n";
– This code segment produces the output:43
– Since post-increment was used
34
Shorthand Operators Pre-Increment in Action
• Now using Pre-increment:
int n = 2, valueProduced;
valueProduced = 2 * (++n); cout << valueProduced << "\n"; cout << n << "\n";
– This code segment produces the output:63
– Because pre-increment was used
35
Console Input/Output
• I/O objects: cin, cout
• Defined in the C++ library called <iostream>
– Must have these lines (called pre-processor directives) near start of file
#include <iostream> using namespace std;
– Tells C++ to use appropriate library so we canuse the I/O objects cin, cout
36
Console Input/Output
• Console Output– What can be outputted?– Any data can be outputted to display screen
• Variables• Constants or Literals• Expressions (which can include all of above)
– cout << numberOfGames << " games played.";
(2 values are outputted: ‘value’ of variable numberOfGames, literal string “ games played.”)
• Cascading: multiple values in one cout
37
Console Input/Output
• Formatting Output– Formatting numeric values for output– Values may not display as you’d expect!
cout << " The price is $ " << price << "\n";– If price (declared double) has value 78.5, you
might get:• The price is $78.500000 or:• The price is $78.5
– We must explicitly tell C++ how to outputnumbers in our programs!
38
Console Input/Output
• Formatting Output– ‘Magic Formula’ to force decimal sizes:
cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2);
– These statements force all future continued values:
• To have exactly two digits after the decimal place
– Example: cout << “The price is $” << price << endl;
– Now results in the following: The price is $78.50
39
Console Input/Output
• Input Using cin– ‘>>’ (extraction operator) points opposite– No literals allowed for cin. Must input ‘to a vari
able’
cin >> num;
– Waits on-screen for keyboard entry– Value entered at keyboard is ‘assigned’ to nu
m
40
Program Style
• Bottom-line ( 底線 ): Make programs easy to read and modify
• Comments, two methods:– // Two slashes indicate entire line is to be ignored– /*Delimiters indicates everything between is ignored*/
• Identifier naming– ALL_CAPS for constants– lowerToUpper for variables– Most important: MEANINGFUL NAMES!
41
Libraries
• C++ Standard Libraries #include <Library_Name> ( 標頭檔 )– Directive to ‘add’ contents of library file to
your program– #include is called ‘preprocessor directive’ ( 前端
處理程式指令 )– Executes before compiler, and simply ‘copies’
library file into your program file
• C++ has many libraries– Input/output, math, strings, etc.
42
Namespaces ( 名稱空間 )
• Namespaces defined:– Collection of name definitions
• Examples:– Includes entire standard library of name definiti
ons #include <iostream>
using namespace std;
– Can specify just the objects we want #include <iostream> using std::cin;
using std::cout;
43
Summary 1
• C++ is case-sensitive
• Use meaningful names– For variables and constants
• Variables must be declared before use– Should also be initialized
• Use care in numeric manipulation– Precision, parentheses, order of operations
• #include C++ libraries as needed
44
Summary 2
• Object cout– Used for console output
• Object cin– Used for console input
• Use comments to aid understanding ofyour program– Do not overcomment
45
ASCII 碼
46
擴充字元集 (Extended Character Set)
47
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 打開 Microsoft Visual C++ 6.0
打開 MS Visual C++ 6.0
48
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project ( 專案 )-1
1選擇 下拉視窗 File 下的 New 選項
49
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project - 2
3
2
選擇 Console 模式的 project
輸入 project 的名稱
50
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project -3
4
51
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project -4
5
新增檔案到 Project
52
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project -5
67
選擇新增檔案的類型為 .cpp 即 C++ 程式
輸入新增檔案為 .cpp 即 C++ 程式
53
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project -5
8
9
10
按兩下即可在右邊視窗編輯
選擇程式視窗
編輯你的程式
54
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project -6
11
編輯你的程式
55
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project -7
12
產生程式的執行檔
56
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project -8
13Compile 的結果
57
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project -9
14
執行程式
58
如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE)
• 產生一個 Console mode project -10
15
執行程式