Chapter 2: Basic Elements of C++ PDF
Document Details
Uploaded by WelcomePrologue
Universiti Malaya
Tags
Summary
This chapter covers the basic elements of C++ programming, including functions, special symbols, data types, assignment statements, and input/output statements. The document also includes examples of C++ programs.
Full Transcript
23.10.2020 Objectives In this chapter, you will:...
23.10.2020 Objectives In this chapter, you will: – Become familiar with functions, special symbols, and identifiers in C++ Chapter 2: – Explore simple data types Basic Elements of C++ – Discover how a program evaluates arithmetic expressions – Learn about assignment statements – Become familiar with the string data type C++ Programming: From Problem Analysis to Program Design, Sixth Edition 2 Objectives (cont’d.) Introduction – Learn about assignment statements Computer program – Become familiar with the string data type – Sequence of statements whose objective is to accomplish – Learn about input and output statements a task – Become familiar increment and decrement operators Programming – Learn how to use preprocessor directives – Process of planning and creating a program – Learn how to debug syntax errors Real-world analogy: a recipe for cooking – Explore how to properly structure a program, including using comments to document a program C++ Programming: From Problem Analysis to Program Design, Sixth Edition 3 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 4 A C++ Program A C++ Program (cont’d.) Sample run: C++ Programming: From Problem Analysis to Program Design, Sixth Edition 5 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 6 1 23.10.2020 A C++ Program (cont’d.) A C++ Program (cont’d.) C++ Programming: From Problem Analysis to Program Design, Sixth Edition 7 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 8 A C++ Program (cont’d.) The Basics of a C++ Program Variable: a memory location whose contents can be Function (or subprogram): collection of statements; changed when executed, accomplishes something – May be predefined or standard Syntax rules: rules that specify which statements (instructions) are legal or valid Figure 2-2 Memory allocation Semantic rules: determine the meaning of the instructions Programming language: a set of rules, symbols, and special words Figure 2-3 Memory spaces after the statement length = 6.0; executes C++ Programming: From Problem Analysis to Program Design, Sixth Edition 9 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 10 Comments Special Symbols Comments are for the reader, not the compiler Token: the smallest individual unit of a program Two types: written in any language – Single line: begin with // C++ tokens include special symbols, word symbols, // This is a C++ program. and identifiers // Welcome to C++ Programming. Special symbols in C++ include: – Multiple line: enclosed between C++ Programming: From Problem Analysis to Program Design, Sixth Edition 11 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 12 2 23.10.2020 Reserved Words (Keywords) Identifiers Reserved word symbols (or keywords): Identifier: the name of something that appears in a – Cannot be redefined within program program – Cannot be used for anything other than their intended use – Consists of letters, digits, and the underscore character (_) Examples: – Must begin with a letter or underscore – int – float C++ is case sensitive – double – NUMBER is not the same as number – char Two predefined identifiers are cout and cin – const – void Unlike reserved words, predefined identifiers may be – return redefined, but it is not a good idea C++ Programming: From Problem Analysis to Program Design, Sixth Edition 13 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 14 Identifiers (cont'd.) Whitespaces Legal identifiers in C++: Every C++ program contains whitespaces – first – Include blanks, tabs, and newline characters – conversion Used to separate special symbols, reserved words, – payRate and identifiers Proper utilization of whitespaces is important – Can be used to make the program more readable C++ Programming: From Problem Analysis to Program Design, Sixth Edition 15 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 16 Data Types Simple Data Types Data type: set of values together with a set of Three categories of simple data operations – Integral: integers (numbers without a decimal) C++ data types fall into three categories: Can be further categorized: – char, short, int, long, bool, unsigned – Simple data type char, unsigned short, unsigned int, – Structured data type unsigned long – Pointers – Floating-point: decimal numbers – Enumeration type: user-defined data type C++ Programming: From Problem Analysis to Program Design, Sixth Edition 17 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 18 3 23.10.2020 Simple Data Types (cont’d.) int Data Type Examples: -6728 0 78 +763 Cannot use a comma within an integer Different compilers may allow different ranges of – Commas are only used for separating items in a list values C++ Programming: From Problem Analysis to Program Design, Sixth Edition 19 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 20 bool Data Type char Data Type bool type The smallest integral data type – Two values: true and false Used for single characters: letters, digits, and special – Manipulate logical (Boolean) expressions symbols true and false Each character is enclosed in single quotes – Logical values – 'A', 'a', '0', '*', '+', '$', '&' bool, true, and false A blank space is a character – Reserved words – Written ' ', with a space left between the single quotes C++ Programming: From Problem Analysis to Program Design, Sixth Edition 21 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 22 char Data Type (cont’d.) Floating-Point Data Types Different character data sets exist C++ uses scientific notation to represent real ASCII: American Standard Code for Information numbers (floating-point notation) Interchange – Each of 128 values in ASCII code set represents a different character – Characters have a predefined ordering based on the ASCII numeric value Collating sequence: ordering of characters based on the character set code C++ Programming: From Problem Analysis to Program Design, Sixth Edition 23 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 24 4 23.10.2020 Floating-Point Data Types (cont’d.) Floating-Point Data Types (cont’d.) float: represents any real number Maximum number of significant digits (decimal – Range: -3.4E+38 to 3.4E+38 (four bytes) places) for float values: 6 or 7 double: represents any real number Maximum number of significant digits for double: – Range: -1.7E+308 to 1.7E+308 (eight bytes) 15 Minimum and maximum values of data types are Precision: maximum number of significant digits system dependent – Float values are called single precision – Double values are called double precision C++ Programming: From Problem Analysis to Program Design, Sixth Edition 25 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 26 Arithmetic Operators, Operator Data Types and Variables Precedence, and Expressions To declare a variable, must specify the data type it C++ arithmetic operators: will store – + addition Syntax: dataType identifier; – - subtraction Examples: – * multiplication – / division int counter; – % modulus (or remainder) operator double interestRate; char grade; +, -, *, and / can be used with integral and floating- point data types Use % only with integral data types C++ Programming: From Problem Analysis to Program Design, Sixth Edition 27 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 28 Arithmetic Operators, Operator Order of Precedence Precedence, and Expressions (cont’d.) When you use / with integral data types, the integral All operations inside of () are evaluated first result is truncated (no rounding) *, /, and % are at the same level of precedence and Arithmetic expressions: contain values and are evaluated next arithmetic operators + and – have the same level of precedence and are evaluated last Operands: the number of values on which the operators will work When operators are on the same level – Performed from left to right (associativity) Operators can be unary (one operand) or binary (two 3 * 7 - 6 + 2 * 5 / 4 + 6 means operands) (((3 * 7) – 6) + ((2 * 5) / 4 )) + 6 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 29 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 30 5 23.10.2020 Expressions Mixed Expressions Integral expression: all operands are integers Mixed expression: – Yields an integral result – Has operands of different data types – Example: 2 + 3 * 5 – Contains integers and floating-point Floating-point expression: all operands are floating- Examples of mixed expressions: point 2 + 3.5 – Yields a floating-point result 6 / 4 + 3.9 – Example: 12.8 * 17.5 - 34.50 5.4 * 2 – 13.6 + 18 / 2 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 31 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 32 Mixed Expressions (cont’d.) Type Conversion (Casting) Evaluation rules: Implicit type coercion: when value of one type is – If operator has same types of operands automatically changed to another type Evaluated according to the type of the operands Cast operator: provides explicit type conversion – If operator has both types of operands static_cast(expression) Integer is changed to floating-point Operator is evaluated Result is floating-point – Entire expression is evaluated according to precedence rules C++ Programming: From Problem Analysis to Program Design, Sixth Edition 33 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 34 Type Conversion (cont’d.) string Type Programmer-defined type supplied in ANSI/ISO Standard C++ library Sequence of zero or more characters enclosed in double quotation marks Null (or empty): a string with no characters Each character has a relative position in the string – Position of first character is 0 Length of a string is number of characters in it – Example: length of "William Jacob" is 13 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 35 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 36 6 23.10.2020 Variables, Assignment Statements, Allocating Memory with Constants and Input Statements and Variables Data must be loaded into main memory before it can Named constant: memory location whose content be manipulated can’t change during execution Storing data in memory is a two-step process: Syntax to declare a named constant: – Instruct computer to allocate memory – Include statements to put data into memory In C++, const is a reserved word C++ Programming: From Problem Analysis to Program Design, Sixth Edition 37 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 38 Allocating Memory with Constants Putting Data into Variables and Variables (cont’d.) Variable: memory location whose content may Ways to place data into a variable: change during execution – Use C++’s assignment statement Syntax to declare a named constant: – Use input (read) statements C++ Programming: From Problem Analysis to Program Design, Sixth Edition 39 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 40 Assignment Statement Assignment Statement (cont’d.) The assignment statement takes the form: Expression is evaluated and its value is assigned to the variable on the left side A variable is said to be initialized the first time a value is placed into it In C++, = is called the assignment operator C++ Programming: From Problem Analysis to Program Design, Sixth Edition 41 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 42 7 23.10.2020 Saving and Using the Value of an Declaring & Initializing Variables Expression To save the value of an expression: Not all types of variables are initialized automatically – Declare a variable of the appropriate data type Variables can be initialized when declared: – Assign the value of the expression to the variable that was int first=13, second=10; declared char ch=' '; Use the assignment statement double x=12.6; Wherever the value of the expression is needed, use All variables must be initialized before they are used the variable holding the value – But not necessarily during declaration C++ Programming: From Problem Analysis to Program Design, Sixth Edition 43 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 44 Input (Read) Statement Input (Read) Statement (cont’d.) cin is used with >> to gather input Using more than one variable in cin allows more than one value to be read at a time Example: if feet and inches are variables of type This is called an input (read) statement int, this statement: The stream extraction operator is >> cin >> feet >> inches; For example, if miles is a double variable – Inputs two integers from the keyboard cin >> miles; – Places them in variables feet and inches respectively – Causes computer to get a value of type double and places it in the variable miles C++ Programming: From Problem Analysis to Program Design, Sixth Edition 45 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 46 Increment and Decrement Operators Increment operator: increase variable by 1 – Pre-increment: ++variable – Post-increment: variable++ Decrement operator: decrease variable by 1 – Pre-decrement: --variable – Post-decrement: variable— What is the difference between the following? x = 5; x = 5; y = ++x; y = x++; C++ Programming: From Problem Analysis to Program Design, Sixth Edition 47 C++ Programming: From Problem Analysis to Program Design, Sixth Edition 48 8 23.10.2020 Output Output (cont’d.) The syntax of cout and