Download presentation

Presentation is loading. Please wait.

Published byBrittany Wiggins Modified over 4 years ago

1
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 1 Chapter 2 Elementary Programming

2
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 2 Motivations In the preceding chapter, you learned how to create, compile, and run a program. Starting from this chapter, you will learn how to solve practical problems programmatically. Through these problems, you will learn primitive data types and related subjects, such as variables, constants, data types, operators, expressions, and input and output.

3
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 3 Objectives F To write C++ programs to perform simple calculations (§2.2). F To read input from the keyboard (§2.3). F To use identifiers to name elements in the program (§2.4). F To use variables to store data (§§2.5-2.6). F To program with assignment statements and assignment expressions (§2.6). F To name constants using the const keyword and #define directive (§2.7). F To declare variables using numeric data types (§2.8). F To use operators to write numeric expressions (§2.8). F To convert numbers to a different type using casting (§2.9). F To represent character using the char type (§2.10). F To become familiar with C++ documentation, programming style, and naming conventions (§2.12). F To distinguish syntax errors, runtime errors, and logic errors (§2.13). F To debug logic errors (§2.14).

4
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 4 Introducing Programming with an Example Listing 2.1 Computing the Area of a Circle This program computes the area of the circle. ComputeArea Run

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

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

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

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

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

10
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 10 Reading Input from the Keyboard You can use the cin object to read input from the keyboard. ComputeArea1 Run

11
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 11 Reading Multiple Input in One Statement ComputeAverage Run

12
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 12 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.

13
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 13 Variables // Compute the first area radius = 1.0; area = radius * radius * 3.14159; cout << area; // Compute the second area radius = 2.0; area = radius * radius * 3.14159; cout << area;

14
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 14 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;

15
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 15 Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a;

16
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 16 Declaring and Initializing in One Step F int x = 1; F double d = 1.4;

17
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 17 Named Constants const datatype CONSTANTNAME = VALUE; const double PI = 3.14159; const int SIZE = 3;

18
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 18 Numerical Data Types

19
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 19 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);

20
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 20 Synonymous Types short int is synonymous to short. unsigned short int is synonymous to unsigned short. unsigned int is synonymous to unsigned. long int is synonymous to long. unsigned long int is synonymous to unsigned long. For example, short int i = 2; is same as short i = 2;

21
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 21 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;

22
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 22 octal and hex literals By default, an integer literal is a decimal number. To denote an octal integer literal, use a leading 0 (zero), and to denote a hexadecimal integer literal, use a leading 0x or 0X (zero x). For example, the following code displays the decimal value 65535 for hexadecimal number FFFF and decimal value 8 for octal number 10. cout << 0xFFFF << " " << 010;

23
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 23 why called floating-point? The float and double types are used to represent numbers with a decimal point. Why are they called floating-point numbers? These numbers are stored into scientific notation. 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 Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 24 Numeric Operators

25
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 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 Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 26 Remainder Operator Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? You can find that day is Tuesday using the following expression:

27
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 27 Example: Displaying Time Write a program that obtains hours and minutes from seconds. DisplayTime Run

28
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 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 Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 29 Arithmetic Expressions is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

30
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 30 Example: Converting Temperatures Write a program that converts a Fahrenheit degree to Celsius using the formula: FahrenheitToCelsius Run

31
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 31 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

32
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 32 Increment and Decrement Operators OperatorNameDescription ++varpreincrementThe expression (++var) increments var 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.

33
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 33 Increment and Decrement Operators, cont.

34
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 34 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.

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

36
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 36 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)

37
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 37 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

38
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 38 NOTE The GNU and Visual C++ compilers will give a warning when you narrow a type unless you use static_cast to make the conversion explicit.

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

40
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 40 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;

41
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 41 Read Characters To read a character from the keyboard, use cout << "Enter a character: "; char ch; cin >> ch;

42
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 42 Escape Sequences for Special Characters

43
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 43 Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

44
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 44 ASCII Character Set, cont. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

45
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 45 Casting between char and Numeric Types int i = ' a ' ; // Same as int i = (int) ' a ' ; char c = 97; // Same as char c = (char)97;

46
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 46 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

47
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 47 Note It is worthwhile to note that the ASCII for lowercase letters are consecutive integers starting from the code for 'a', then for 'b', 'c',..., and 'z'. 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'. For a lowercase letter ch, its corresponding uppercase letter is static_cast ('A' + (ch - 'a')).

48
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 48 Problem: 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.

49
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 49 Problem: 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

50
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 50 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

51
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 51 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

52
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 52 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

53
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 53 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

54
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 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; 6 remainingAmount Suppose amount is 11.56 11 numberOfOneDollars 2 numberOfQuarters remainingAmount updated animation

55
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 55 Problem: 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

56
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200 56 Programming Style and Documentation F Appropriate Comments F Naming Conventions F Proper Indentation and Spacing Lines F Block Styles

Similar presentations

© 2019 SlidePlayer.com Inc.

All rights reserved.

To make this website work, we log user data and share it with processors. To use this website, you must agree to our Privacy Policy, including cookie policy.

Ads by Google