vc课件程序设计_第1页
vc课件程序设计_第2页
vc课件程序设计_第3页
vc课件程序设计_第4页
vc课件程序设计_第5页
已阅读5页,还剩64页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、4/25/2022 1Chapter 2. C+ Syntax and Semantics, and the Program Development Process4/25/2022 2BOOK P26BOOK P26A collection of one or more functions.A collection of one or more functions.Must have a function named main.Must have a function named main.Execution of the program begins with the main Execu

2、tion of the program begins with the main function.function.Operating system calls the main function.Operating system calls the main function.C+ Program Structure4/25/2022 3First Examplev#include vusing namespace std;vint Square( int );vint Cube( int );vint main()vv cout The square of 27 is Square(27

3、) endl;v cout and the cube of 27 is Cube(27) endl;v return 0;vvint Square( int n )vv return n * n;vvint Cube( int n )vv return n * n * n;v4/25/2022 4Syntax and SemanticsvSyntaxvThe formal rules governing how valid instructions are written in a programming language.vSemanticsvThe set of rules that de

4、termines the meaning of instructions written in a programming language.4/25/2022 5Syntax - IdentifiersvA name associated with a function or data object and used to refer to that function or data object.vMake up of letters(A-Z, a-z), digits(0-9), and the underscore character, but must begin with a le

5、tter or underscore.4/25/2022 6Meta-languages P29vOne of the oldest computer-oriented meta-languages is BNF.vBNF is an extremely simple language, but that simplicity leads to syntax definitions that can be long and difficult to read.vAnother Meta-language, Syntax template.4/25/2022 7Syntax template -

6、 Identifier4/25/2022 8Identifier Template4/25/2022 9Syntax Template DefinitionvCan be downloaded from website: v vSynTemp.pdf4/25/2022 10Identifier ExamplesvCorrect id : vsum_of_squares j9 box_22AvGetData Bin3D4 count A a vIncorrect id : v40Hours Get Datavbox-22 cost_in_$ int vage# 2000TaxRate Age-O

7、f-CatvIdentifier examples P32vReserved Words cannot be used as identifiers.vIdentifiers are case sensitive.vUsing Meaningful, Readable Identifiers P324/25/2022 11C+ Reserved WordsP683 Appendix A4/25/2022 12 012345678910.01234567字节和位内存以字节(byte)为单元组成每个字节有一个地址一个字节一般由8个二进制位(bit)组成每个二进位的值是0或14/25/2022 13

8、Data and Data TypesvData is stored in the computers memory.vEach memory location has a unique address.vData type A specific set of data values, along with a set of operations on those values.vC+ allows programmers to define their own data types.vEach piece of data must be of a specific data type.4/2

9、5/2022 14C+ Data TypesBuilt-in TypesUser-defined TypesC+ built-in data types are oganized into simple types, structured types, and address types. 4/25/2022 15C+ Data Typesstructuredarray struct union class addresspointer referencesimple integral enumchar short int long boolfloatingfloat double long

10、double4/25/2022 16C+ Simple Data Typessimple typesintegralfloating char short int long bool enum float double long doubleunsigned4/25/2022 17Standard Data Types in C+vIntegral Typesvrepresent whole numbers and their negativesvdeclared as int, short, or longvFloating Typesvrepresent real numbers with

11、 a decimal pointvdeclared as float, or doublevCharacter Typevrepresents single charactersvdeclared as char4/25/2022 18Samples of C+ Data Valuesint sample values 4578 -45780float sample values95.27495.2659521E-3-95E-195.213E2char sample values B d 4? *4/25/2022 19Declarationsva statement that associa

12、tes an identifier with a data object, a function, or a data type so that the programmer can refer to that item by name.vEvery identifier in a program (scope) must be different from all others.vEvery identifier must be declared before it is used.4/25/2022 20DeclarationsvA declaration always ends with

13、 a semicolon.vchar letter;vchar ch;vYou can declare several variables in one statement.v char letter, ch;4/25/2022 21vDeclarationsvint n; /静态分配静态分配vint* nPtr = new int; /动态分配动态分配vvoid instructions();vbool user_says_yes();4/25/2022 22What is a Variable?vA variable is a location in memory which we can

14、 refer to by an identifier, and in which a data value that can be changed is stored. vdeclaring a variable means specifying both its name and its data typevBook p36 figure 2-1 char mychar;4/25/2022 23What Does a Variable Declaration Do?A declaration tells the compiler to allocate enough memory to ho

15、ld a value of this data type, and to associate the identifier with this ageOfDog;float taxRateY2K;char middleInitial;4 bytes for taxRateY2K1 byte for middleInitial4/25/2022 24vConstantsvLiteral value vAny constant value.veg: A string 100 3.1415926vNamed constant(符号常量符号常量)vusing const mo

16、difier in declaration statement. veg:v const int VOTING_AGE = 18 ; v const string BOOK_TITLE=programming in C+;v#define VOTING_AGE = 184/25/2022 25What is a Named Constant?vA named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be change

17、d is stored. vv VALID CONSTANT DECLARATIONSv const string STARS = “*” ;v const float NORMAL_TEMP = 98.6 ; v const char BLANK = ;v const int VOTING_AGE = 18 ; v const float MAX_HOURS = 40.0 ;4/25/2022 26使用符号常量的好处是:使用符号常量的好处是:(1)含义清楚;)含义清楚;(2)在需要改变一个常量时能做到)在需要改变一个常量时能做到“一改全一改全 改改”。4/25/2022 27First Tw

18、o Typesvchar a single charactervA a 1 ? nvRepresenting a character in a character set ( ASCII , EBCDIC , Unicode , GB ).vstring sequences of charactersvProgramming C+ hellon a vstring template library using #include vwith null character(0) termination4/25/2022 28ASCII (American Standard CodeInformat

19、ion Interchange)美国标准信息交换码美国标准信息交换码P695 Appendix D如如 A65 A65, a a9797, 048, n 048, n1010Date Type Char4/25/2022 29Date Type Char(1)字符型变量用来存放字符常量。)字符型变量用来存放字符常量。(2)字符变量的定义形式如下:)字符变量的定义形式如下: char c1=a,c2=A; 字符常量的定义形式如下:字符常量的定义形式如下: const char BLANK= ;(3)在所有的编译系统中都规定以一个字)在所有的编译系统中都规定以一个字节来存放一个字符,或者说一个字符

20、变量节来存放一个字符,或者说一个字符变量在内存中占一个字节。在内存中占一个字节。4/25/2022 30An Example#include int main( )char a=a; /char a=97;coutChar a takes bytes: sizeof(a)endl;coutvalue of a is: aendl;int b;coutInt b takes bytes: sizeof(b)endl;coutvalue of b is: bendl;b=a;coutvalue of b is: bendl;return 0;4/25/2022 31Output of Progra

21、mvChar a takes bytes: 1vvalue of a is: avInt b takes bytes: 4vvalue of b is: -858993460vvalue of b is: 974/25/2022 32Data Type Stringva string is a sequence of characters enclosed in double quotes v字符窜变量用来存放字符窜常量。字符窜变量用来存放字符窜常量。v字符窜变量的定义形式如下:字符窜变量的定义形式如下:v string book_title;v book_title=“Programming

22、 in C+”;v 字符窜常量的定义形式如下:字符窜常量的定义形式如下:v const string NULL_LINE=“ ”;4/25/2022 33More About Stringstring is not a built-in (standard) typeit is a programmer-defined data typeit is provided in the C+ standard library #include string operations includecomparing 2 string valuesjoining one string to another

23、4/25/2022 34String Concatenation (+)vconcatenation is a binary operation that uses the + operator vOperands - string literals, string values , char data.vat least one of the operands must be a string variable or named constant-the other operand can be string type or char type ve.g. A+B v hello +worl

24、d v are incorrect.4/25/2022 35Concatenation Example const string WHEN = “Tomorrow” ; const char EXCLAMATION = ! ; string message1 ; string message2 ; message1 = “Yesterday “ ; message2 = “and “ ; message1 = message1 + message2 + WHEN + EXCLAMATION ;4/25/2022 36Concatenation Example string message1 ;

25、 string message2 ; message1 = “Yesterday “ ;/valid message2 = message1 + “a” + “b” ;/invaild message2 = “a” + “b” + message1 ;4/25/2022 37Giving a Value to a VariableYou can assign (give) a value to a variable by using the assignment operator = VARIABLE DECLARATIONS string firstName ;char middleInit

26、ial ;char letter ;int ageOfDog;VALID ASSIGNMENT STATEMENTS firstName = “Fido” ;middleInitial = X ;letter = middleInitial ;ageOfDog = 12 ;4/25/2022 38What is an Expression in C+?vAn expression is a valid arrangement of variables, constants, and operators. vin C+ each expression can be evaluated to co

27、mpute a value of a given typevvthe value of the expression v 9 + 5 is 14 Variable = ExpressionFirst, Expression on right is evaluated.Then the resulting value is stored in the memory location of Variable on left.Variable left value ( lvalue )Type of expression must be compatible with variableAssignm

28、ent Operator SyntaxCorrect Assignment Examplesv string firstName, v middleName,v lastName,v name;v name = firstName+middleName+lastName;v Note: string + means concatenation.v In assigning a value to a string variable, the expression to the right of = must be a string expression, a literal string, or

29、 a char.4/25/2022 41Insertion Operator ( )vvariable cout is predefined to denote an output stream that goes to the standard output device (display screen)vthe insertion operator called “put to” takes 2 operandsv vthe left operand is a stream expression, such as cout. The right operand is an expressi

30、on of simple type or a string constant vIn header file : v ostream cout;4/25/2022 42Output StatementsSYNTAXThese examples yield the same output:cout “The answer is “ ;cout 3 * 4 ;cout “The answer is “ 3 * 4 ;cout Expression Expression . . . ;4/25/2022 43Output StatementsBook p424/25/2022 44About out

31、putvStart a new line use endl manipulator or insert a special char n .v e.g. v couthelloworld; helloworldv couthelloendlworldendl ; hellov worldv couthellonworldn ; hellov worldvOutput in a string use to represent .v e.g. v coutAl Butch Jones Al Butch Jones 45Control Charactersvin addition to the pr

32、intable characters, character sets also have nonprintable control characters to control the screen, printer, and other hardware vin C+ programs, control characters are represented by escape sequences. Each escape sequence is formed by a backslash followed by one or more additional characters 46Some

33、Escape SequencesnNewline (Line feed in ASCII)tHorizontal tabbBackspaceaAlert (bell or beep)BackslashSingle quote (apostrophe)”Double quote (quotation mark)0Null character (all zero bits)dddOctal equivalent (3 octal digits)xdddHexadecimal equivalent (1 or more hex digits for integer value of characte

34、r)4/25/2022 47CommentsvComments help anyone who must read the program, the compiler ignores comments.vTwo forms of comments v/* block comment */ v/ line commentvWriting fully commented programs is good programming style.vMaking comments concise and readable, dont ment4/25/2022 48Is compilation the f

35、irst step?vNo. Before your source program is compiled, it is first examined by the preprocessor tovremove all comments from source codevhandle all preprocessor directives-they begin with the # character such as #include vtells preprocessor to look in the standard include directory for the header fil

36、e called iostream and insert its contents into your source code 4/25/2022 49Using LibrariesvA library has 2 partsvInterface (stored in a header file) tells what items are in the library and how to use them.vImplementation (stored in another file) contains the definitions of the items in the library.

37、v#include vRefers to the header file for the iostream library needed for use of cout and endl.4/25/2022 50NamespacevNamespace scope of identifiersvAn identifier declared within a namespace block can be accessed directly only by statements within that block.vTwo ways to access identifiers of another

38、named namespace P504/25/2022 51/ * / PrintName program/ This program prints a name in two different formats/ *#include / for cout and endl#include / for data type stringusing namespace std;const string FIRST = “Herman”; / Persons first nameconst string LAST = “Smith”; / Persons last nameconst char M

39、IDDLE = G; / Persons middle initialC+ Program 4/25/2022 52Continuedint main( ) string firstLast; / Name in first-last format string lastFirst; / Name in last-first format firstLast = FIRST + “ “ + LAST ; cout “Name in first-last format is “ endl firstLast endl; lastFirst = LAST + “, “ + FIRST + ; co

40、ut “Name in first-last format is “ endl lastFirst MIDDLE . endl; return 0; 4/25/2022 53Output of Program Name in first-last format is Herman Smith Name in last-first-initial format is Smith, Herman G.4/25/2022 54ExercisevWhich of the following statements about the C+ main function is false? vA)Every program must have a function named main. vB)Program execution begins with the first executable statement in the m

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论