Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 1 Chapter 2 Primitive Data Types and Operations.

Similar presentations


Presentation on theme: "Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 1 Chapter 2 Primitive Data Types and Operations."— Presentation transcript:

1 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 1 Chapter 2 Primitive Data Types and Operations

2 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 2 Objectives F To write C++ programs to perform simple calculations (§2.2). F To read input from the keyboard using the cin object (§2.3). F To simplify programming by omitting the std:: prefix (§2.4). F To use identifiers to name variables, constants, functions, and classes (§2.5). F To use variables to store data (§§2.6-2.7). F To program with assignment statements and assignment expressions (§2.7). F To use constants to store permanent data (§2.8).

3 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 3 Objectives (cont.) F To declare variables using numeric data types (§2.9). F To use operators to write numeric expressions (§2.9). F To convert numbers to a different type using casting (§2.10). F To represent character using the char type (§2.11). F To become familiar with C++ documentation, programming style, and naming conventions (§2.13). F To distinguish syntax errors, runtime errors, and logic errors (§2.14). F To debug logic errors (§2.15).

4 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 4 Example Program Listing 2.1: Computing the Area of a Circle This program computes the area of the circle. ComputeArea Run

5 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 5 Trace a Program Execution #include int main() { double radius; double area; // Step 1: Assign radius radius = 20; // Step 2: Compute area area = radius * radius * 3.14159; // Step 3: Display the area std::cout << "The area is "; std::cout << area << std::endl; } no value radius allocate memory for radius animation

6 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 6 Trace a Program Execution no value radius memory animation #include int main() { double radius; double area; // Step 1: Assign radius radius = 20; // Step 2: Compute area area = radius * radius * 3.14159; // Step 3: Display the area std::cout << "The area is "; std::cout << area << std::endl; } no value area allocate memory for area

7 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 7 Trace a Program Execution 20 radius no value area assign 20 to radius animation #include int main() { double radius; double area; // Step 1: Assign radius radius = 20; // Step 2: Compute area area = radius * radius * 3.14159; // Step 3: Display the area std::cout << "The area is "; std::cout << area << std::endl; }

8 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 8 Trace a Program Execution 20 radius memory 1256.636 area compute area and assign it to variable area animation #include int main() { double radius; double area; // Step 1: Assign radius radius = 20; // Step 2: Compute area area = radius * radius * 3.14159; // Step 3: Display the area std::cout << "The area is "; std::cout << area << std::endl; }

9 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 9 Trace a Program Execution 20 radius memory 1256.636 area print a message to the console animation #include int main() { double radius; double area; // Step 1: Assign in radius radius = 20; // Step 2: Compute area area = radius * radius * 3.14159; // Step 3: Display the area std::cout << "The area is "; std::cout << area << std::endl; }

10 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 10 Reading Input from the Keyboard ] ComputeArea1 Run #include int main() { double radius; double area; // Step 1: Input radius std::cout << “Please enter radius.” << std::endl; std::>> radius; // Step 2: Compute area area = radius * radius * 3.14159; // Step 3: Display the area std::cout << "The area is "; std::cout << area << std::endl; }

11 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 11 Omitting the std:: Prefix F You have noticed that std::cout, std::endl, and std::cin all start with std::. F std means the standard namespace. C++ divides the world into “namespaces” to resolve potential naming conflicts. (E.g., “Kaki” may occur twice in Chaminade, but 20 in Honolulu) F std::cout means that cout belongs to the standard namespace. F To avoid typing “std::”: –add the statement: using namespace std;

12 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 12 Omitting the std:: Prefix (cont.) #include using namespace std; int main() { double radius; double area; // Step 1: Input radius cout << “Please enter radius.” << endl; cin >> radius; // Step 2: Compute area area = radius * radius * 3.14159; // Step 3: Display the area cout << "The area is "; cout << area << endl; }

13 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 13 Identifiers F An identifier is a sequence of characters that consists of letters, digits, and underscores (_). F An identifier must start with a letter or an underscore. It cannot start with a digit. F An identifier cannot be a reserved word. (See Appendix A, “C++ Keywords,” for a list of reserved words.) F An identifier can be of any length, but your C++ compiler may impose some restriction. Use identifiers of 31 characters or fewer to ensure portability.

14 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 14 Variables // Compute the first area radius = 1.0; area = radius * radius * 3.14159; std::cout << area; // Compute the second area radius = 2.0; area = radius * radius * 3.14159; std::cout << area;

15 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 15 Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable;

16 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 16 Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a;

17 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 17 Declaring and Initializing in One Step F int x = 1; F double d = 1.4;

18 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 18 Named Constants const datatype CONSTANTNAME = VALUE; const double PI = 3.14159; const int SIZE = 3;

19 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 19 Numerical Data Types

20 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 20 sizeof Function You can use the sizeof function to find the size of a type. For example, the following statement displays the size of int, long, and double on your machine. cout << sizeof(int) << " " << sizeof(long) << " " << sizeof(double);

21 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 21 Synonymous Types F short int is same as short. F unsigned short int is same as unsigned short. F unsigned int is same as unsigned. F long int is same as long. F unsigned long int is same as unsigned long. F E.g., short int i = 2; is same as short i = 2;

22 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 22 Numeric Literals A literal is a constant value that appears directly in a program. For example, 34, 1000000, and 5.0 are literals in the following statements: int i = 34; long k = 1000000; double d = 5.0;

23 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 23 What Are floating-point? F The float and double types are used to represent numbers with a decimal point. F Why are they called floating-point numbers? F These numbers are stored in scientific notation. F When a number such as 50.534e+1 is converted into scientific notation such as 5.0534, its decimal point is moved (i.e., floated) to a new position.

24 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 24 Numeric Operators

25 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 25 Integer Division +, -, *, /, and % 5 / 2 yields an integer 2. 5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division)

26 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 26 Remainder Operator 3 % 2 = 1 8 % 2 = 0 33 % 2 = 1 Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is it in 10 days? You can find that day is Tuesday using the following expression:

27 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 27 Your Turn: Displaying Time Write a program that obtains hours and minutes from seconds. DisplayTime Run

28 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 28 Overflow When a variable is assigned a value that is too large to be stored, it causes overflow. For example, executing the following statement causes overflow, because the largest value that can be stored in a variable of the short type is 32767. 32768 is too large. short value = 32767 + 1;

29 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 29 Underflow When a variable is assigned a value that is too small to be stored, it causes underflow. For example, executing the following statement causes underflow, because the smallest value that can be stored in a variable of the short type is -32768. - 32769 is too small. short value = -32769;

30 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 30 Arithmetic Expressions Convert the following formulas into C++ statements d = v 0 + (1/2)gt 2 f = Gm 1 m 2 / r 2 days = 365 x years feet = 5280 x miles volume = (4/3)пr 3

31 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 31 Your Turn: Converting Temperatures Given celsius value, calculate the equivalent fahrenheit value: C = (5/9)(F – 32)

32 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 32 Arithmetic Expressions (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

33 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 33 Operator Precedence  What is the value of x? 1.x = 2 + 3 * 4; 2.x = 2 * 3 + 4; 3.x = 2 / 3 + 4 * 5; 4.X = 2 * (3 + 4) / 5;

34 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 34 Operator Precedence (...) +, - (unary) *, / +, - =

35 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 35 Shorthand Assignment Operators OperatorExampleEquivalent +=i += 8i = i + 8 -=f -= 8.0f = f - 8.0 *=i *= 8i = i * 8 /=i /= 8i = i / 8 %=i %= 8i = i % 8

36 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 36 Increment and Decrement Operators OperatorNameDescription ++varpreincrementThe expression increments by 1 and evaluates to the new value in var after the increment. var++postincrementThe expression (var++) evaluates to the original value in var and increments var by 1. --varpredecrementThe expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var--postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1.

37 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 37 Increment and Decrement Operators, cont.

38 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 38 Increment and Decrement Operators, cont. Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i.

39 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 39 Numeric Type Conversion Consider the following statements: short i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2;

40 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 40 Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is long double, the other is converted into long double. 2. Otherwise, if one of the operands is double, the other is converted into double. 3. Otherwise, if one of the operands is float, the other is converted into float. 4. Otherwise, if one of the operands is unsigned long, the other is converted into unsigned long. 5. Otherwise, if one of the operands is long, the other is converted into long. 6. Otherwise, if one of the operands is unsigned int, the other is converted into unsigned int. 7. Otherwise, both operands are converted into int.

41 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 41 Type Casting Implicit casting double d = 3; (type widening) Explicit casting int i = static_cast (3.0); (type narrowing) int i = (int)3.9; (Fraction part is truncated)

42 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 42 NOTE Casting does not change the variable being cast. For example, d is not changed after casting in the following code: double d = 4.5; int i = static_cast (d); // d is not changed

43 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 43 Example: Keeping Two Digits After Decimal Points Write a program that displays the sales tax with two digits after the decimal point. SalesTax Run

44 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 44 Character Data Type char letter = 'A'; //(ASCII) char numChar = '4'; //(ASCII) NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding character. For example, the following statements display character b. char ch = 'a'; cout << ++ch;

45 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 45 Read Characters To read a character from the keyboard, use cout << "Enter a character: "; char ch; cin >> ch;

46 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 46 Escape Sequences for Special Characters

47 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 47 Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

48 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 48 ASCII Character Set, cont. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

49 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 49 Casting between char and Numeric Types int i = ' a ' ; // Same as int i = (int) ' a ' ; char c = 97; // Same as char c = (char)97;

50 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 50 Numeric Operators on Characters The char type is treated as if it is an integer of the byte size. All numeric operators can be applied to char operands. A char operand is automatically cast into a number if the other operand is a number or a character. For example, the following statements int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51 cout << "i is " << i << endl; // i is decimal 101 int j = 2 + 'a'; // (int)'a' is 97 cout << "j is " << j << endl; cout << j << " is the ASCII code for character " << static_cast (j) << endl; Display i is 101 j is 99 99 is the ASCII code for character c

51 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 51 Note F The ASCII number for lowercase letters are consecutive integers starting from the code for 'a', then for 'b', 'c',..., and 'z'. F The same is true for the uppercase letters. Furthermore, the ASCII code for 'a' is greater than the code for 'A'. So 'a' - 'A' is the same as 'b' - 'B'. F For a lowercase letter ch, its corresponding uppercase letter is static_cast ('A' + (ch - 'a')).

52 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 52 Example: Computing Loan Payments ComputeLoanRun This program lets the user enter the interest rate, number of years, and loan amount and computes monthly payment and total payment.

53 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 53 Example: Monetary Units This program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies. Your program should report maximum number of dollars, then the maximum number of quarters, and so on, in this order. ComputeChangeRun

54 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 54 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 1156 remainingAmount remainingAmount initialized Suppose amount is 11.56

55 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 55 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 1156 remainingAmount Suppose amount is 11.56 11 numberOfOneDollars numberOfOneDollars assigned animation

56 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 56 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 56 remainingAmount Suppose amount is 11.56 11 numberOfOneDollars remainingAmount updated animation

57 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 57 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 56 remainingAmount Suppose amount is 11.56 11 numberOfOneDollars 2 numberOfOneQuarters numberOfOneQuarters assigned animation

58 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 58 Trace ComputeChange int remainingAmount = (int)(amount * 100); // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount; 6 remainingAmount Suppose amount is 11.56 11 numberOfOneDollars 2 numberOfQuarters remainingAmount updated animation

59 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 59 Example: Displaying Current Time Write a program that displays current time in GMT in the format hour:minute:second such as 1:45:19. The time(0) function in the ctime header file returns the current time in seconds elapsed since the time 00:00:00 on January 1, 1970 GMT, as shown in Figure 2.1. This time is known as the Unix epoch because 1970 was the year when the Unix operating system was formally introduced. ShowCurrentTime Run

60 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 60 Programming Style and Documentation Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles


Download ppt "Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 013225445X 1 Chapter 2 Primitive Data Types and Operations."

Similar presentations


Ads by Google