1 / 49

Chapter 2

Chapter 2. Jason C. H. Chen, Ph.D. Professor of MIS School of Business Administration Gonzaga University Spokane, WA 99258 chen@gonzaga.edu. Problem. C++ Solution. O-O (UML). C++ Features. Problem. C++ Solution. // miles.cpp // Converts distance in miles to kilometers.

gareth
Download Presentation

Chapter 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2 Jason C. H. Chen, Ph.D. Professor of MIS School of Business Administration Gonzaga University Spokane, WA 99258 chen@gonzaga.edu

  2. Problem C++ Solution

  3. O-O (UML) C++ Features Problem C++ Solution

  4. // miles.cpp // Converts distance in miles to kilometers. #include <iostream> // class for stream input/output using namespace std; // use the standard namespace int main() // start of main function { const float KM_PER_MILE= 1.609; // 1.609 km in a mile float miles, // input: distance in miles kms; // output: distance in kilometers // Get the distance in miles. cout << "Enter the distance in miles: "; cin >> miles; // Convert the distance to kilometers. kms = KM_PER_MILE* miles; // Display the distance in kilometers. cout << "The distance in kilometers is " << kms << endl; return 0; }

  5. Create your first C++ program • Create a folder on your workstation • bmis342 or mbus674 • Invoke Visual C++ compiler • Select Startthen Programs then Visual Studio • Click on File then New • On New pop-up menu, select Files • Select C++ Source Files • On the right hand side menu • Enter miles on the File Name: • Select c:\bmis342 or c:\mbus674 on the Location:

  6. 2.1 C++ Language Elements (1). COMMENTS • Comments make a program easier to understand • // Used to signify a comment on a single line • /* Text text */use if commentson multilines • Don’t embed comments within /* */ comments

  7. (2). Compiler Directives • Stream data type • Object that is a stream of characters • Defined iniostream • Entered on the keyboard (cin) • Displayed on monitor (cout) • #include • Compiler directive • Processed at compilation time • Instructs compiler on what you want in the program • #include <iostream> • Adds library files to program • Used with < > • supports cin cout • #include “money.cpp” • Also “ “ user defined

  8. (3). Function Headerint main() (4). Main body{}

  9. (5). Memory Location • Each variable is associated with a memory location and it stores a value e.g., KM_PER_MILE = 1.609; sum = 0; item = 1; sum = sum + item;

  10. Declarations • Direct compiler on requirements • Based on data needs (data identifiers) • Each identifier needed must be declared • Comma used to separate identifiers • cin and cout are undeclared identifiers • Special elements called streams • cin - input stream , cout - output stream • Included with the iostream not declared

  11. Executable Statements • cout display output • cout << “Enter the distance in miles: ”; • cin get input • cin >> miles; • Assignment • kms = KM_PER_MILE * miles;

  12. 2.2 (6) Reserved Words and Identifiers (Variables) • Reserved words have special meanings • Can NOT be used for other purposes (const, float and void are some examples) (see App. B, p.716) • Identifiers (variables) • Used to store data by the program (user defined) • Rules of naming an identifier • 1. Begin with a letter or underscore • 2. Consist of letters, digits, or underscores only • 3. Do not use a C++ reserved word • Valid identifiers - letter, letter1, _letter • Invalid identifiers - 1letter, const, hell o (Exercises 2.2, p.48)

  13. Reserved Words and Identifiers • Special symbols • C++ has rules for special symbols • = * ; { } ( ) // << >> • Appendix B • Examples of reserved words • Special characters

  14. (7). Upper and Lower Case • C++ case sensitive • Compiler differentiates upper & lower case • Identifiers can be either • Be careful though (cost != Cost) • Blank spaces • Use space to make program readable • Use care in placing spaces

  15. 2.3 (8). Data Types and Declarations • Three Data Types • Language-defined data types • Predefined data types • System-defined data types (Libraries) • User-defined data types • Why use different data types? • Different types allow programmers to use resources more efficiently • Standard arithmetic and relational operations are available for these types

  16. Data Types (ADTs) Standard Structured Primitive Standard Enumerated String Vector List Array Struct Class Integer Float Character Boolean Data Hierarchy in the C++ Language An abstract data type or ADT, describes the data attributes and behavior of its objects.

  17. 2.3 Data Types and Declarations • Predefined data types • int (integers) • range from -32768 to 32767 • Positive or negative whole numbers • 1000 12 199 100000 • INT_MAX - largest int allowed by compiler • INT_MIN, LONG_MAX, LONG_MIN • Other integers types • short: typically uses less bits (-32768 to 32767) • long: typically uses more bits (-2147483648 to 2147483647)

  18. Data Types and Declarations • float (real numbers) • Positive or negative decimal numbers • 10.5 1.2 100.02 99.88 • C++ provides three floating-point types • float (3.4E +/- 38 (7 digits) • double (1.7E +/- 308 (15 digits) • long double (1.7E +/- 4932 (40 digits)

  19. Data Types and Declarations • Predefined data types • bool (boolean) • true • false • char (Characters) • Represent characters • Individual character value (letter or number) • Character literal enclosed in single quotes ‘A’ • Ordinal types • int bool char • Values can be listed

  20. Data Types and Declarations • Character type char isrelated to the integer types • Characters are encoded using a scheme where an integer represents a particular character • ASCII is the dominant encoding scheme • Examples (Appendix A, p.731) • ‘ ' (space) encoded as 32 • '+' encoded as 43 • 'A' encoded as 65 • 'Z' encoded as 90 • ’a' encoded as 97 • ’z' encoded as 122

  21. string Class • String object data type • A literal string constant is a sequence of zero or more characters enclosed in double quotes • "Are you aware?\n" • Individual characters of string are stored in consecutive memory locations • The null character ('\0') is appended to strings so that the compiler knows where in memory strings ends

  22. string Class • String literal • “A” • “1234” • “Enter the distance” • Additional data types included in library #include <string> • Various operations on strings

  23. Declarations • Identifiers should be • Short enough to be reasonable to type (single word is norm) • Standard abbreviations are fine (but only standard abbreviations) • Long enough to be understandable • When using multiple word identifiers capitalize the first letter of each word

  24. Declarations • Examples char response; int minelement; float score; float temperature; int i; int n; char c; float x;

  25. (8). Constant Declarations • Types of constants • integer • float • char • bool • string objects • Associate meaningful terms • const float KM_PER_MILE = 1.609; • const float PAYRATE = 10.25;

  26. Hello.cpp (p.55) // FILE: Hello.cpp // DISPLAYS A USER'S NAME #include <iostream> #include <string> using namespace std; int main () { char letter1, letter2; string lastName; // Enter letters and print message. cout << "Enter 2 initials and last name: "; cin >> letter1 >> letter2 >> lastName; cout << "Hello " << letter1 << ". " << letter2 << ". " << lastName << "! "; cout << "We hope you enjoy studying C++." << endl; return 0; }

  27. Hello.cpp (p.55) // Hello.cpp : Defines the entry point for the console application. #include <iostream> #include <string> using namespace std; int main() { // Local data ... char letter1, letter2; // input and output: first two initials string last_name; // input and output: last name // Enter letters and print message. cout << "Enter 2 initials and last name: "; cin >> letter1 >> letter2 >> last_name; cout << "Hello " << letter1 << ". " << letter2 << ". " << last_name << "! "; cout << "We hope you enjoy studying C++." << endl; return 0; } Sample Run: Enter 2 initials and last name: CJMCDONALD Hello C. J. MCDONALD! We hope you enjoy studying C++. Press any key to continue Sample Run: Enter 2 initials and last name: CJMC DONALD Hello C. J. MC! We hope you enjoy studying C++. Press any key to continue

  28. Reading & Displaying string Objects #include <string> getline (cin, lastName, ‘\n’); reads all characters typed in from the keyboard up to the new line into the string object

  29. 2.4 Executable Statements • Memory status • Before and after • Assignments • Form: result = expression; • sizeInSqyards = metersToYards * sizeInMeters; • sum = sum + item;

  30. Arithmetic Operators • + Addition • - Subtraction • * Multiplication • / Division • % Modulus

  31. Input / Output Operations • Input • #include <iostream> library • cin >> sizeInSqmeters; • Extracted from cin (input stream) • >> Directs input to variable • cin associated with keyboard input (stdin) • Used with int, float, char, bool and strings

  32. Data Types and cin • Don’t mix types with cin int x; cin >> x; Keyboard input 16.6 Value placed in x would be 16

  33. Other Characteristics of cin • Leading blanks ignored (floats, int, char, bool and strings) • Char read 1 at a time (1 non blank) • Case issues • int or float will read until space • Stings same as int and float

  34. General Form for cin Form: cin >> dataVariable; cin >> age >> firstInitial;

  35. Program Output • Output stream cout • << Output operator (insertion operator) • cout << “my height in inches is: “ << height; • Blank lines • endl; or “\n”; Form: cout << dataVariable;

  36. 2.6 Arithmetic Expressions • int data type • + - * /, Assignment, input and output on int • % Only used with int • Examples of integer division 15 / 3 = 5 15 / 2 = 7 0 / 15 = 0 15 / 0 undefined

  37. Modulus and Integer • Used only with integer and yields remainder • Examples of integer modulus 7 % 2 = 1 299 % 100 = 99 49 % 5 = 4 15 % 0 undefined

  38. Mixed-type Assignments • Expression evaluated • Result stored in the variable on the left side • C++ can mix types float a, b, x; int m, n; a=10; b=5; x = m / n;

  39. Expressions With Multiple Operators • Operator precedence tells how to evaluate expressions • Standard precedence order • () Evaluated first, if nested innermost done first • * / % Evaluated second. If there are several, then evaluate from left-to-right • + - Evaluate third. If there are several, then evaluate from left-to-right

  40. Mathematical Formulas in C++ • a = bc not valid C++ syntax • * Operator a = b * c; • m = y - b x - a • ( ) And / m = (y - b) / (x - a);

  41. Hello-2.cpp (next slide) • C++ assignment • formatted_output.cpp (handout) • puchase_Lastname_Firstname.cpp (HW) • Exercises 2.6 (p.82) • #1,2

  42. // Hello-2.cpp : Defines the entry point for the console application. #include <iostream> #include <string> using namespace std; int main() { // Local data ... char letter1, letter2; // input and output: first two initials string last_name; // input and output: last name // Enter letters and print message. cout << "Enter 2 initials and last name: "; cin >> letter1 >> letter2; getline(cin, last_name, '\n'); cout << "Hello " << letter1 << ". " << letter2 << ". " << last_name << "! "; cout << "We hope you enjoy studying C++." << endl; return 0; }

  43. Coin Collection Case Study • Problem statement • Saving nickels and pennies and want to exchange these coins at the bank so need to know the value of coins in dollars and cents. • Analysis • Count of nickels and pennies in total • Determine total value • Use integer division to get dollar value • / 100

  44. Coin Collection Case Study • Analysis (cont) • Use modulus % to get cents value • % 100 • Design • Prompt for name • Get count of nickels and pennies • Compute total value • Calculate dollars and cents • Display results

  45. Coin Collection Case Study • Implementation • Write C++ code of design • Verify correct data types needed • Mixed mode types and promotion • Testing • Test results using various input combinations

  46. // coins.cpp : Defines the entry point for the console application. (p.81) // Determines the value of a coin collection #include <iostream> #include <string> using namespace std; int main() { // Local data ... string name // input: sister's first name int pennies; // input: count of pennies int nickels; // input: count of nickels int dollars; // output: value of coins in dollars int change; // output: value of coins in cents int totalCents; // total cents represented // Prompt sister for name. cout << "Enter your first name: "; cin >> name; // Read in the count of nickels and pennies. cout << "Enter the number of nickels: "; cin >> nickels; cout << "Enter the number of pennies: "; cin >> pennies; // Compute the total value in cents. totalCents = 5 * nickels + pennies; // Find the value in dollars and change. dollars = totalCents / 100; change = totalCents % 100; // Display the value in dollars and change. cout << "Good work " << name << '!' << endl; cout << "Your collection is worth " << dollars << ” dollars and ” << change << " cents." << endl; return 0; }

  47. 2.7 Interactive Mode, Batch and Data Files (skip this section - UNIX)

  48. 2.8 Common Programming Errors • Syntax • Programs rarely compile • Something always goes wrong • Systematic solutions • Compiler not descriptive • Look at line number before and after error • Watch missing ; and }

  49. Common Programming Errors • Syntax errors • Logic errors • Program functions differently than you expect • Run-time errors • Illegal operation (divide by 0)

More Related