Presentation is loading. Please wait.

Presentation is loading. Please wait.

EGR 2261 Unit 2 Basic Elements of C++

Similar presentations


Presentation on theme: "EGR 2261 Unit 2 Basic Elements of C++"— Presentation transcript:

1 EGR 2261 Unit 2 Basic Elements of C++
Read Malik, Chapter 2. Homework #2 and Lab #2 due next week. Quiz next week. Handouts: Quiz 1,

2 A Quick Look at a C++ Program
This is Lab01Rectangle. Have them open the project on their PCs. (Remind about difference between opening a file and opening a project.) C++ Programming: From Problem Analysis to Program Design, Seventh Edition

3 A Quick Look at a C++ Program (cont’d.)
Sample run: C++ Programming: From Problem Analysis to Program Design, Seventh Edition

4 A Quick Look at a C++ Program (cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition

5 A Quick Look at a C++ Program(cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition

6 A Quick Look at a C++ Program (cont’d.)
Variable: a memory location whose contents can be changed. Figure 2-2 Memory allocation after the four variable declaration statements ? ? ? ? I modified the book’s figure by adding the ? on the uninitialized boxes, because they will hold some unkown value. Figure 2-3 Memory spaces after the statement length = 6.0; executes ? ? ? C++ Programming: From Problem Analysis to Program Design, Seventh Edition

7 The Basics of a C++ Program
Function (or subprogram): a collection of statements that, when executed, accomplishes something useful. May be predefined or user-defined. Syntax rules: rules that specify which statements (instructions) are legal or valid. Semantic rules: determine the meaning of the instructions. Programming language: a set of rules, special symbols, and reserved words. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

8 Special Symbols Some special symbols in C++ :
This is not a complete list of special symbols. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

9 Reserved Words (Keywords)
Reserved words (or keywords): You cannot redefine these words. You cannot use them for anything other than their intended use. Examples: int using return See Appendix A (next slide) in textbook for complete list. Note that reserved words are color-coded blue in previous program. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

10

11 Tokens Tokens: the smallest meaningful units of a program.
C++ tokens include special symbols, reserved words, and identifiers. Reserved words Identifier Special symbol C++ Programming: From Problem Analysis to Program Design, Seventh Edition

12 Identifiers Identifier: the name of something that appears in a program. Consists of letters, digits, and the underscore character (_). Must begin with a letter or underscore. C++ is case sensitive. NUMBER is not the same as number. Two predefined identifiers are cout and cin. Unlike reserved words, predefined identifiers may be redefined, but it is not a good idea. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

13 Identifiers (cont’d.) Examples of legal identifiers in C++: first
payRate2 Employee_Salary C++ Programming: From Problem Analysis to Program Design, Seventh Edition

14 Comments Comments are for the reader, not the compiler. Two types:
Single line: begin with // // This is a C++ program. // Welcome to C++ Programming. Multiple line: enclosed between /* and */ /* You can include comments that can occupy several lines. */ C++ Programming: From Problem Analysis to Program Design, Seventh Edition

15 Whitespace Every C++ program contains whitespace.
Includes blanks, tabs, and newline characters. Whitespace must separate reserved words and identifiers from each other. Proper use of whitespace (such as indenting) can also make programs more readable. Examine whitespace in previous program, and show examples of whitespace that can or cannot be removed. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

16 Data Types Data type: set of values together with a set of allowed operations on those values. C++ data types fall into three categories: Simple data types Structured data types Pointers For the next few weeks we’ll mostly use simple data types. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

17 Simple Data Types Three categories of simple data:
Integral: integers (numbers without a decimal). Can be further categorized: char, short, int, long, long long, bool, unsigned char, unsigned short, unsigned int, unsigned long Floating-point: decimal numbers. float, double, long double Enumeration type: user-defined data type. We won’t use. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

18 Partial Hierarchy of Data Types
Simple Data Types Integral (int, bool, char, …) Floating-Point (float, double, …) Enumeration Structured Data Types Pointers

19 Simple Data Types (cont’d.)
The ranges shown above are typical. Different compilers may allow different ranges of values. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

20 int Data Type Examples of int data:
-6728 78 +763 Do not use commas within numbers. Typing 1,430 instead of 1430 will usually cause an error. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

21 bool Data Type The bool type has only two possible values: true and false. For keeping track of true/false (Boolean) information, such as whether a person’s age is greater than 21. This is considered an integral data type because it’s actually implemented as a 0 for false and a 1 for true. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

22 char Data Type Used for single characters: letters, digits, and special symbols. Each character is enclosed in single quotes: 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character. Written ' ', with a space left between the single quotes. Note that there’s a difference between single quotes and double quotes. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

23 char Data Type (cont’d.)
Different character sets exist, but we’ll use ASCII. ASCII: American Standard Code for Information Interchange Each of 128 integer values (from 0 to 127) represents a different character; see Appendix C in textbook (next slide). Collating sequence: Characters have a predefined ordering based on the ASCII numeric value. For example, the ASCII code for 'A' is 65 and the ASCII code for ‘D' is 68, so we can say that 'A' < ‘D'. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

24

25 Floating-Point Data Types
Non-integer numbers can be entered or displayed using decimal notation or using a modified scientific notation. Demo by modifying rectangle program so length is first 6E1 and then 6E6. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

26 Floating-Point Data Types (cont’d.)
Typical Range: -3.4E+38 to 3.4E+38 (four bytes) double Typical Range: -1.7E+308 to 1.7E+308 (eight bytes) Ranges of data types are system-dependent. We’ll generally use double when we want a floating-point number. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

27 Review: Simple Data Types
Three categories of simple data: Integral: integers (numbers without a decimal) Can be further categorized: char, short, int, long, long long, bool, unsigned char, unsigned short, unsigned int, unsigned long Floating-point: decimal numbers float, double, long double Enumeration type: user-defined data type. We won’t use. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

28 Arithmetic Operators Some C++ arithmetic operators:
+ addition - subtraction * multiplication / division % modulus (or remainder) You can use +, -, *, and / with integral and floating-point data types. You can use % only with integral data types. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

29 Arithmetic Expressions
Arithmetic expressions combine values (operands) and arithmetic operators to yield a result. Example: 12.8 * Arithmetic expressions can be: Integral expressions: all operands are integers. Floating-point expressions: all operands are floating-point. Mixed expressions: some operands are integer, some are floating-point. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

30 Integral Expressions Integral expression: an arithmetic expression in which all operands are integers. Yields an integer result. Example: * 5 Caution: When you use / with integers, the integer result is truncated (no rounding). Example: 7 / 2 yields a result of 3 C++ Programming: From Problem Analysis to Program Design, Seventh Edition

31 Quotient and Remainder
We know that 7 ÷ 2 = 3.5 Recall that another way to say this is that 7 ÷ 2 = 3 with a remainder of 1. In this example, 3 is called the quotient and 1 is called the remainder. In C++, using the / operator with integers yields the quotient. Example: In C++, 7 / 2 yields a result of 3 And using the % operator with integers yields the remainder. Example: In C++, 7 % 2 yields a result of 1 -This is how we learned to do division before we were taught floating-point numbers (decimals). -Note that the % operator has nothing to do with percentages.

32 Floating-Point Expressions
Floating-point expression: an arithmetic expression in which all operands are floating-point. Yields a floating-point result. Example: 7.0 / 2.0 The expression above yields 3.5 Another example: 12.8 * C++ Programming: From Problem Analysis to Program Design, Seventh Edition

33 Operator Precedence and Associativity
Operators inside parentheses are evaluated first. *, /, and % have the same level of precedence and are evaluated next. + and – have the same level of precedence and are evaluated next. Arithmetic operators on the same level of precedence are performed from left to right. (They have “left-to-right associativity.”) Example: Evaluate the following expression: 3 * * 5 / 4 + 6 Then re-evaluate it with parentheses around the 6+2. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

34 Mixed Expressions Mixed expression: an arithmetic expression that has operands of different data types (some integer, some floating-point). Examples: 6 / 5.4 * 2 - ( ) / 2 See next slide for rules on how C++ evaluates these. Have them evaluate each one after reviewing rules on next slide. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

35 Mixed Expressions (cont’d.)
Evaluation rules: The precedence and associativity rules from above still apply. If an operator has the same types of operands: It is evaluated according to the type of the operands. If operator has both types of operands: Integer is “promoted” to floating-point. Operator is evaluated. Result is floating-point. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

36 Type Conversion and Casting
Implicit type conversion (also called coercion) occurs when C++ automatically changes a value of one type to another type. We’ve seen an example of this with mixed expressions. C++ also lets you perform explicit type conversion using the cast operator: static_cast<dataTypeName>(expression) C++ Programming: From Problem Analysis to Program Design, Seventh Edition

37 Type Conversion (Casting) (cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition

38 Unary Versus Binary Operators
The arithmetic operators we’ve discussed are all binary operators: they take two operands. Some operators are unary operators (one operand). In fact, + and – can be either binary or unary, depending on the context. Unary – is negation. Example: –2 * 3 Another example: * –3 C++ Programming: From Problem Analysis to Program Design, Seventh Edition

39 Other Operators As well as the arithmetic operators discussed above, C++ has many other operators. See Appendix B (next slide) in the textbook for a complete list that shows precedence and associativity. Note from this list that unary + and – have higher precedence than binary + and – . Unfortunately the table in Appendix B contains a few typos, so be sure to fix them using the list of textbook typos on the course website. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

40

41 Review: Data Types Recall that C++ data types fall into three categories: Simple data types (int, char, bool, double, …) Structured data types Pointers For the next few weeks we’ll mostly use simple data types, plus one structured data type called the string type. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

42 string Type A string is a sequence of zero or more characters enclosed in double quotation marks. Contrast with char data type, which is a single character inside single quotation marks. A string’s length is the number of characters in it. Example: length of "William Jacob" is 13 Each character has a position in the string, with the first character at position 0. Example: In "William Jacob", the character ‘m’ is at position 6. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

43 string Type (cont’d.) Unlike the simple data types discussed earlier, string is not built into the core C++ language. It’s a programmer-defined type supplied in the C++ Standard Library. So the five data types that we will use extensively are int char bool double string C++ Programming: From Problem Analysis to Program Design, Seventh Edition

44 Variables The expressions we’ve looked at used constant numeric values. Example: 2 * 3.5 In most programs you’ll also use variables, which are named memory locations whose values can change as the program runs. Example: 2 * payRate When naming your variables, be sure to follow the rules we saw earlier for identifiers. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

45 Declaring Variables In C++ you must declare each variable’s data type before you can use the variable. Syntax to declare one or more variables: C++ Programming: From Problem Analysis to Program Design, Seventh Edition

46 Putting Data into Variables
A variable is said to be initialized the first time you place a value into it. A variable that has not been initialized will hold an unpredictable “garbage” value. Visual Studio gives an error message if you use an uninitialized variable in an expression. Ways to place data into a variable: Use an assignment statement. Use input (read) statements. Demo use of an unitialized variable. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

47 Assignment Statement The assignment statement takes the form:
The expression is evaluated and its value is assigned to the variable on the left side. Examples: dailyRate = ; annualRate = 365 * dailyRate; In C++, = is called the assignment operator. Demo that you’ll get an error if you try to say = dailyRate. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

48 Assignment Statement (cont’d.)
This is from Lab01DataTypes. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

49 Declaring & Initializing Variables
You can use the assignment operator to initialize a variable in the same statement that declares it. Examples: int first = 13, second = 10; char ch = ' '; double x = 12.6; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

50 Assignment versus Equality
The = operator in C++ has a different meaning from the meaning it has in your math classes. Example: in a math class, the following statement cannot be true: x = x + 1; But this is a perfectly good (and frequently used) C++ statement. It tells the program to increase x’s value by 1.

51 Increment and Decrement Operators
The increment operator ++ increases a variable by 1. Example: The statement x++; does the same thing as the statement x = x + 1; Similarly, the decrement operator -- decreases a variable’s value by 1. Example: The statement x--; does the same thing as the statement x = x - 1; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

52 Pre- and Post-Increment/Decrement
These operators’ behavior depends on whether they’re placed before or after the variable name. Pre-increment: ++variable increments the variable, and then uses the incremented value in the expression. Post-increment: variable++ uses the variable’s original value in the expression, and then increments the variable. What is the difference between the following? Similarly for pre-decrement (--variable) and post-decrement (variable--). x = 5; y = ++x; x = 5; y = x++; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

53 Input (Read) Statement
cin is used with >> to let the user enter a value. This is called an input statement (or read statement). The operator >> is the stream extraction operator. For example, if miles is a double variable, the following statement causes computer to get a value of type double from the keyboard and place it in the variable miles: cin >> miles; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

54 Input (Read) Statement (cont’d.)
A single input statement can assign values to more than one variable. Example: if feet and inches are variables of type int, the following statement reads two integers from the keyboard and places these integer values in feet and inches respectively. : cin >> feet >> inches; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

55 This is Lab01ConvertLength.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition

56 Output Statement cout is used with << to display values on the screen: This is called an output statement. The operator << is the stream insertion operator. The expression is evaluated and its value is printed at the current cursor position on the screen. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

57 Manipulators in Output Statements
You can use manipulators to format the output. Example: the manipulator endl causes the cursor to move to beginning of the next line. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

58 Escape Sequences in Output Statements
Escape sequences are another way to format output. Example: The new line character is '\n' cout << "Hello there."; cout << "My name is James."; Output: Hello there.My name is James. cout << "Hello there.\n"; Output : Hello there. My name is James. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

59 Escape Sequences in Output Statements (cont’d.)
Chapter 3 is devoted to I/O and will cover lots more details on cin, cout, manipulators, …. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

60 The Standard Library The core C++ language has a relatively small number of built-in operations. Many other useful operations are provided as a collection of files called the C++ Standard Library. These library files make your job easier, because they save you from having to re-invent the wheel when you want to perform common tasks. A big part of becoming a C++ programmer is learning about the many library files in the Standard Library. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

61 The Standard Library (cont’d.)
Each library file (or “header file”) has a name, which is typically written inside angle brackets. Examples: <iostream> <string> <cmath> The next slides show how to tell the compiler that you want to use operations from one or more of these files. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

62 Preprocessor Directives
Your programs will often contain preprocessor directives. These are commands that the preprocessor program executes before your program is compiled. All preprocessor directives begin with #. No semicolon at the end of these directives. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

63 The #include Directive
The most common preprocessor directive is #include, which is how you tell the compiler that you want to use a Standard Library file. Syntax to include a header file: For example: #include <iostream> Causes the preprocessor to include the header file iostream in the program. Without this, you could not use cout or cin in your program. Demo the error you’ll get if you try to use cin or cout without this #include. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

64 namespace and Using cin and cout in a Program
cin and cout are declared in the header file iostream, but within the std namespace. To use cin or cout in a program, use the following two statements: #include <iostream> using namespace std; Without that using statement, you would need to type std::cin instead of cin throughout your program. Demo what you’d need to do if you didn’t have the using statement. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

65 Using the string Data Type in a Program
Recall that the string data type is not built into the core C++ language. It’s a programmer-defined type defined in the C++ Standard Library. To use the string type, you need to access its definition from the header file string. Use the following preprocessor directive: #include <string> C++ Programming: From Problem Analysis to Program Design, Seventh Edition

66 The main Function A function is a named block of code that performs some well-defined set of operations. Every C++ program must contain a function named main. This is where execution begins when you run the program. Complex programs contain many functions, but for now most of your programs will only contain the main function. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

67 The main Function (cont’d.)
The first line of a function is called the function’s heading: int main() The statements enclosed between the curly braces { and } form the function’s body. As an example of a program with more than one function, look at Lab06MoreVowels. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

68 Named Constants Named constant: memory location whose content cannot change during execution. Syntax to declare a named constant: By convention, constant identifiers are all upper-case. Use Lab02Circle to demo how trying to change PI’s value will give an error. Also show that you’ll get an error if you don’t initialize PI when you declare it. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

69 Syntax Errors Syntax rules: indicate what is legal and what is not legal. Example of a syntax rule: Every C++ statement must end with a semicolon. The compiler finds and reports syntax errors during compilation. It won’t let you run the program until you fix these errors. int x; //Line 1 int y //Line 2: Syntax error C++ Programming: From Problem Analysis to Program Design, Seventh Edition

70 Semantic Errors Semantic rules: set of rules that gives meaning to a language. A program with no syntax errors may still not produce correct results. Example: * 5 and (2 + 3) * 5 are both syntactically correct expressions, but have different meanings. So if you use one of these expressions where you should use the other one, your program will produce incorrect results. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

71 Prompt Lines Prompt lines are statements that tell the user what to do. cout << "Please enter a number between 1 and 10 and " << "press the return key." << endl; cin >> num; Always include a prompt line when you want the user to enter some input. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

72 Documentation A well-documented program is easier to understand and modify. Two keys to good documentation: Use comments. Choose meaningful variable names. Comments should: Explain the purpose of the program. Identify who wrote it, and when. Explain the purpose of particular statements whose meaning is not obvious. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

73 Documentation (cont’d.)
Variable names should be self-documenting: Example: use CENTIMETERS_PER_INCH instead of X. Avoid run-together words, such as annualsale. This is hard to read. Solution: Either capitalize the beginning of each new word: annualSale Or insert an underscore just before a new word: annual_sale C++ Programming: From Problem Analysis to Program Design, Seventh Edition

74 Compound Assignment Statements
In addition to the simple assignment operator =, C++ provides several compound assignment operators, including: += -= *= /= %= Simple assignment statement: x = x * y; Equivalent compound assignment statement: x *= y; Their sole purpose is to provide more concise notation. But you don’t need to use them. C++ Programming: From Problem Analysis to Program Design, Seventh Edition


Download ppt "EGR 2261 Unit 2 Basic Elements of C++"

Similar presentations


Ads by Google