Download presentation
Presentation is loading. Please wait.
Published byPhilippa Meghan Nichols Modified over 9 years ago
1
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 1-5
2
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 2 © 2006 Pearson Education. All Rights Reserved 1 장. 컴퓨터와 프로그래밍 소개 2 장. C++ 소개 3 장. 수식 4 장. 의사 결정 5 장. 루프
3
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 3 © 2006 Pearson Education. All Rights Reserved 1 장. 컴퓨터와 프로그래밍 소개 1.1 Why Program? 1.2 Computer Systems: Hardware and Software 1.3 Programs and Programming Languages 1.4 What Is a Program Made of? 1.5 Input, Processing, and Output 1.6 The Programming Process 1.7 Procedural and Object-Oriented Programming
4
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 4 © 2006 Pearson Education. All Rights Reserved From a High-level Program to an Executable File Object Code Linker Executable Code Source Code Preprocessor Modified Source Code Compiler
5
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 5 © 2006 Pearson Education. All Rights Reserved 1.6 The Programming Process 1.Define what the program is to do. 2.Visualize the program running on the computer. 3.Use design tools to create a model of the program. Hierarchy charts, pseudocode, flowcharts, etc. 4.Check the model for logical errors. 5.Write the program source code. 6.Compile the source code.
6
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 6 © 2006 Pearson Education. All Rights Reserved The Programming Process 7. Correct any errors found during compilation. 8. Link the program to create an executable file. 9. Run the program using test data for input. 10. Correct any errors found while running the program. Repeat steps 4 - 10 as many times as necessary. 11. Validate the results of the program. Does the output do what was defined in step 1?
7
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 7 © 2006 Pearson Education. All Rights Reserved 1.7 Procedural and Object- Oriented Programming 절차적 프로그래밍 –Focus is on the process –Procedures/functions are written to process data 객체지향 프로그래밍 –Focus is on objects, which contain data and the means to manipulate the data –Messages are sent to objects to perform operations
8
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 8 © 2006 Pearson Education. All Rights Reserved 2.1 Parts of a C++ Program 2.2 The cout Object 2.3 The #include Directive 2.4 Standard and Prestandard C++ 2.5 Variables, Constants, and the Assignment Statement 2.6 Identifiers 2.7 Integer Data Types 2.8 The char Data Type 2 장. C++ 소개
9
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 9 © 2006 Pearson Education. All Rights Reserved 2.9 The C++ string Class 2.10 Floating-Point Data Types 2.11 The bool Data Type 2.12 Determining the Size of a Data Type 2.13 More on Variable Assignments and Initialization 2.14 Scope 2.15 Arithmetic Operators 2.16 Comments (//, /* */) 2 장. C++ 소개 ( 계속 )
10
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 10 © 2006 Pearson Education. All Rights Reserved comment preprocessor directive which namespace to use beginning of function named main beginning of block for main output statement send 0 back to operating system end of block for main // sample C++ program #include using namespace std; int main() { cout << "Hello, there!"; return 0; } 2.1 Parts of a C++ Program
11
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 11 © 2006 Pearson Education. All Rights Reserved Must #include to create and use string objects Can define string variables in programs string name; Can assign values to string variables with the assignment operator – name = "George"; Can display them with cout – cout << name; 2.9 The C++ string Class
12
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 12 © 2006 Pearson Education. All Rights Reserved 3 장. 수식 3.1 The cin Object 3.2 Mathematical Expressions 3.3 Implicit Type Conversion 3.4 Explicit Type Conversion 3.5 Overflow and Underflow 3.6 Named Constants
13
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 13 © 2006 Pearson Education. All Rights Reserved 3.7 Multiple and Combined Assignment 3.8 Formatting Output 3.9 Working with Characters and String Objects 3.10 Using C-Strings 3.11 More Mathematical Library Functions 3.12 Introduction to Files
14
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 14 © 2006 Pearson Education. All Rights Reserved The cin Object Can be used to input multiple values –cin >> height >> width; Multiple values from keyboard must be separated by spaces or [Enter] Order is important; first value entered is stored in first variable, etc.
15
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 15 © 2006 Pearson Education. All Rights Reserved Type Coercion( 형의 강제변환 ) Coercion: automatic conversion of an operand to another data type Promotion( 승급 ): converts to a higher type Demotion( 강등 ): converts to a lower type
16
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 16 © 2006 Pearson Education. All Rights Reserved 3.4 Explicit Type Conversion Also called type casting Used for manual data type conversion Format static_cast (expression) Example: cout (65); // Displays 'A'
17
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 17 © 2006 Pearson Education. All Rights Reserved // Create a short int initialized to // the largest value it can hold short int num = 32767; cout << num; // Displays 32767 num = num + 1; cout << num; // Displays -32768 Overflow Example
18
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 18 © 2006 Pearson Education. All Rights Reserved Handling Overflow and Underflow Different systems handle the problem differently. They may –display a warning / error message –display a dialog box and ask what to do – stop the program – continue execution with the incorrect value
19
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 19 © 2006 Pearson Education. All Rights Reserved 3.6 Named Constants( 이름 상수 ) Also called constant variables Variables whose content cannot be changed during program execution Used for representing constant values with descriptive names –const double TAX_RATE = 0.0675; –const int NUM_STATES = 50; Often named in uppercase letters
20
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 20 © 2006 Pearson Education. All Rights Reserved const vs. #define #define – C-style of naming constants –#define NUM_STATES 50 –Interpreted by pre-processor rather than compiler –Does not occupy a memory location like a constant variable defined with const –Instead, causes a textual substitution to occur. In above example, every occurrence in program of NUM_STATES will be replaced by 50 no ; goes here
21
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 21 © 2006 Pearson Education. All Rights Reserved 3.7 Multiple and Combined Assignment The assignment operator (=) can be used > 1 time in an expression –x = y = z = 5; Associates right to left –x = (y = (z = 5)); Done Done Done 3 rd 2 nd 1 st
22
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 22 © 2006 Pearson Education. All Rights Reserved 3.9 Working with Characters and String Objects char: holds a single character string: holds a sequence of characters Both can be used in assignment statements Both can be displayed with cout and <<
23
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 23 © 2006 Pearson Education. All Rights Reserved Character Input Reading in a character char ch; cin >> ch; // Reads in any non-blank char cin.get(ch); // Reads in any char cin.ignore() // Skips over next char in // the input buffer
24
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 24 © 2006 Pearson Education. All Rights Reserved String Input Reading in a string object string str; cin >> str; // Reads in a string // with no blanks getline(cin, str); // Reads in a string // that may contain // blanks #include
25
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 25 © 2006 Pearson Education. All Rights Reserved String Operators = Assigns a value to a string string words; words = "Tasty "; + Joins two strings together string s1 = "hot", s2 = "dog"; string food = s1 + s2; // food = "hotdog" += Concatenates a string onto the end of another one words += food; // words now = "Tasty hotdog"
26
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 26 © 2006 Pearson Education. All Rights Reserved 3.10 Using C-Strings C-string is stored as an array of characters Programmer must indicate maximum number of characters at definition –const int SIZE = 5; –char temp[SIZE] = "Hot"; NULL character (\0) is placed after final character to mark the end of the string Programmer must make sure array is big enough for desired use; temp can hold up to 4 characters plus the \0. H o t \0
27
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 27 © 2006 Pearson Education. All Rights Reserved C-String Initialization vs. Assignment A C-string can be initialized at the time of its creation (just like a string object can) const int SIZE = 10; char month[SIZE] = "April"; However, a C-string cannot later be assigned a value using the = operator; you must use the strcpy() function char month[SIZE]; month = "April" // wrong! strcpy(month, "April"); //correct
28
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 28 © 2006 Pearson Education. All Rights Reserved 3.12 Introduction to Files Can use a file instead of keyboard for program input Can use a file instead of monitor screen for program output Files are stored on secondary storage media, such as disk They allow data to be retained between program runs
29
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 29 © 2006 Pearson Education. All Rights Reserved What is Needed to Use Files(5 Steps) 1.Include the fstream header file #include 2. Define a file stream object –ifstream for input from a file ifstream inFile; –ofstream for output to a file ofstream outFile;
30
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 30 © 2006 Pearson Education. All Rights Reserved Open the File 3. Open the file Use the open member function inFile.open("inventory.dat"); outFile.open("report.txt"); Filename may include drive, path info. Output file will be created if necessary; existing output file will be erased first Input file must exist for open to work
31
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 31 © 2006 Pearson Education. All Rights Reserved Use the File 4. Use the file Can use output file object and << to send data to a file outFile << "Inventory report"; Can use input file object and >> to copy data from file to variables inFile >> partNum; inFile >> qtyInStock >> qtyOnOrder;
32
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 32 © 2006 Pearson Education. All Rights Reserved Close the File 5. Close the file Use the close member function inFile.close(); outFile.close(); Don’t wait for operating system to close files at program end –May be limit on number of open files –May be buffered output data waiting to be sent to a file
33
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 33 © 2006 Pearson Education. All Rights Reserved 4 장. 의사결정 ( 조건문 ) 4.1 Relational Operators 4.2 The if Statement 4.3 The if/else Statement 4.4 The if/else if Statement 4.5 Menus 4.6 Nested if Statements 4.7 Logical Operators
34
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 34 © 2006 Pearson Education. All Rights Reserved 4.8 Checking Numeric Ranges with Logical Operators 4.9 Validating User Input 4.10 More About Variable Definitions and Scope 4.11 Comparing Characters and Strings 4.12 The Conditional Operator 4.13 The switch Statement 4.14 Enumerated Data Types 4.15 Testing for File Open Errors
35
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 35 © 2006 Pearson Education. All Rights Reserved Format of the if Statement if (expression) { statement1; statement2; … statementn; } The block inside the braces is called the body of the if statement. If there is only 1 statement in the body, the { } may be omitted. No ; goes here ; goes here
36
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 36 © 2006 Pearson Education. All Rights Reserved if Statement Flow of Control expression 1 or more statements true false
37
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 37 © 2006 Pearson Education. All Rights Reserved Flags Variables that signals conditions Usually implemented as a bool Sometimes implemented as an int The flag value can be both set and tested with if statements
38
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 38 © 2006 Pearson Education. All Rights Reserved Flag Example Example: bool validMonths = true; … if (months < 0) validMonths = false; … if (validMonths) moPayment = total / months;
39
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 39 © 2006 Pearson Education. All Rights Reserved if/else Flow of Control expression statement set 1 true false statement set 2
40
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 40 © 2006 Pearson Education. All Rights Reserved if/else if Format if (expression) { statement set 1; } else if (expression) { statement set 2; } … else if (expression) { statement set n; }
41
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 41 © 2006 Pearson Education. All Rights Reserved 4.6 Nested if Statements An if statement that is part of the if or else part of another if statement Can be used to evaluate > 1 data item or condition if (score < 100) { if (score > 90) grade = 'A'; }
42
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 42 © 2006 Pearson Education. All Rights Reserved Notes on Coding Nested ifs An else matches the nearest if that does not have an else if (score < 100) if (score > 90) grade = 'A'; else... // goes with second if, // not first one Proper indentation helps comprehension
43
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 43 © 2006 Pearson Education. All Rights Reserved switch Statement Format switch (expression) { case exp1: statement set 1; case exp2: statement set 2;... case expn: statement set n; default: statement set n+1; }
44
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 44 © 2006 Pearson Education. All Rights Reserved switch Statement Requirements 1) expression must be a char or an integer variable or an expression that evaluates to an integer value 2) exp1 through expn must be constant integer expressions and must be unique in the switch statement 3) default is optional but recommended
45
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 45 © 2006 Pearson Education. All Rights Reserved How the switch Statement Works expression is evaluated The value of expression is compared against exp1 through expn. If expression matches value expi, the program branches to the statement(s) following expi and continues to the end of the switch If no matching value is found, the program branches to the statement after default:
46
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 46 © 2006 Pearson Education. All Rights Reserved The break Statement Used to stop execution in the current block Also used to exit a switch statement Useful to execute a single case statement without executing statements following it
47
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 47 © 2006 Pearson Education. All Rights Reserved Example switch Statement switch (gender) { case 'f': cout << "female"; break; case 'm': cout << "male"; break; default : cout << "invalid gender"; }
48
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 48 © 2006 Pearson Education. All Rights Reserved 4.15 Testing for File Open Errors After opening a file, test that it was actually found and opened before trying to use it –By testing the file stream object –By using the fail() function
49
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 49 © 2006 Pearson Education. All Rights Reserved Testing the File Stream Object Example: ifstream datafile; datafile.open("customer.dat"); if (!datafile) cout << "Error opening file.\n"; else // proceed to use the file
50
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 50 © 2006 Pearson Education. All Rights Reserved Using the fail() Function Example: ifstream datafile; datafile.open("customer.dat"); if (datafile.fail()) cout << "Error opening file.\n"; else // proceed to use the file
51
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 51 © 2006 Pearson Education. All Rights Reserved 5 장. 루프 ( 반복문 ) 5.1 The Increment and Decrement Operators 5.2 Introduction to Loops: The while Loop 5.3 Counters 5.4 Letting the User Control the Loop 5.5 Keeping a Running Total 5.6 Sentinels
52
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 52 © 2006 Pearson Education. All Rights Reserved 5.7 Using a Loop to Read Data From a File 5.8 The do-while and for Loops 5.9 Deciding Which Loop to Use 5.10 Nested Loops 5.11 Breaking Out of a Loop 5.12 The continue Statement 5.13 Using Loops for Data Validation
53
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 53 © 2006 Pearson Education. All Rights Reserved 5.2 Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while (expression) { statement(s); } If there is only one statement in the body of the loop, the {} can be omitted No ; goes here
54
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 54 © 2006 Pearson Education. All Rights Reserved while Loop Flow of Control true statement(s) false condition
55
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 55 © 2006 Pearson Education. All Rights Reserved Using the eof() Function to Test for the End of a File eof() member function returns true when the previous read encountered the end of file; returns false otherwise Example: datafile >> score; while (!datafile.eof()) { sum += score; datafile >> score; }
56
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 56 © 2006 Pearson Education. All Rights Reserved Problems Using eof() For the eof() function to work correctly using this method, there must be a whitespace (space, tab, or [Enter] ) after the last piece of data Otherwise the end of file will be encountered when reading the final data value and it will not be processed
57
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 57 © 2006 Pearson Education. All Rights Reserved Using the >> Operation The stream extraction operator (>>) returns a value indicating if a read is successful This can be tested to find the end of file since the read “fails” when there is no more data Example: while (datafile >> score) sum += score;
58
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 58 © 2006 Pearson Education. All Rights Reserved do-while Flow of Control statement(s) condition false true
59
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 59 © 2006 Pearson Education. All Rights Reserved The for Loop Pretest loop that executes zero or more times Useful for counter-controlled loop Format: for( initialization; test; update ) { 1 or more statements; }
60
Chapter 1 Starting Out with C++: Early Objects 5/e Slide 60 © 2006 Pearson Education. All Rights Reserved 5.10 Nested Loops A nested loop is a loop inside the body of another loop Example: for (row = 1; row <= 3; row++) { for (col = 1; col <= 3; col++) { cout << row * col << endl; } outer loop inner loop
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.