1 / 58

C/ C++ Basics (I) Variables, Expressions and Assignments

C/ C++ Basics (I) Variables, Expressions and Assignments. Berlin Chen 2003. Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002. Introduction to C++. Programming Languages Low-level languages Machine, assembly High-level languages B, C, C++, ADA, COBOL, FORTRAN

corl
Download Presentation

C/ C++ Basics (I) Variables, Expressions and Assignments

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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 meanings 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”; … } High level language -readable -machine independent (portable) C/C++ Language (Text Files) xxx.cpp Compiler 編譯器 VC++, gcc 00100000 01101010 ….. 01101010 Low level language -unreadable -machine dependent Machine Language (Binary Files)

  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; //結束函數 } 函數標題 函數主體 敘述(statement)以分號結束 函數定義 註解(comment)以“//”為起始 結束函數

  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; } 標頭檔名及 名稱空間 C++ 程式 Enter the amount of your deposit $ 100 In one year, the deposit will grow to $106.9 程式 執行 過程 輸入

  10. Identifiers (識別字) • Identifiers are items defined/used in a program • Keywords (關鍵字)or Reserved Words (保留字) • Variables (變數)、function names (函數名稱)、labels (標記) • 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, ABC123z7,… • 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 start of a block “{” (or a function/procedure) • 通常在程式或每個函式開頭宣告,也可以在程式任意位置用到時才宣告

  14. Variables Memory 1000 numberOfBeans 1004 2108 oneWeight 2112

  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 整數 型態 浮點數 型態 字元或字串 型態 布林數 型態 有效位數及指數範圍不同

  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 any 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 type 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 aboutwhat 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; } C++ 程式 Enter the amount of your deposit $ 100 In one year, the deposit will grow to $106.9 程式 執行 過程 輸入

  25. Escape Sequences(逸出順序、控制碼) • Backslash,(背斜線) \ preceding a character (字元) • Instructs compiler: a special ‘escapecharacter’ (逸出字元) is coming • 逸出字元:字串及字元中無法顯示之字元

  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 (算數運算子) • 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++ automatically17 / 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 tointVar = intVar – 1;

  33. Shorthand OperatorsPost-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 OperatorsPre-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, youmight 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 variable’ cin >> num; • Waits on-screen for keyboard entry • Value entered at keyboard is ‘assigned’ to num

  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 toyour 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 definitions #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 輸入 project 的名稱 3 2 選擇 Console 模式的 project

  50. 如何使用 MS Visual C++ 6.0 之整合程式設計環境 (IDE) • 產生一個 Console mode project -3 4

More Related