Chapter 5 :Operators,Expressions and Statements - Programming Exercises

1. Write a program that converts time in minutes to time in hours  and  minutes.  Use #define or const to create a  symbolic constant for 60. Use a while loop to allow the user to enter values repeatedly and terminate the loop if a value for the time of 0 or less is entered.

#include <stdio.h>

int main(void) {
    const int minperhour = 60;
    int minutes, hours, mins;
    printf("Enter the number of minutes to convert: ");
    scanf("%d", &minutes);
    while (minutes > 0) {
        hours = minutes / minperhour;
        mins = minutes % minperhour;
        printf("%d minutes = %d hours, %d minutes\n", minutes, hours, mins);
        printf("Enter next minutes value (0 to quit): ");
        scanf("%d", &minutes);
    }
    printf("Bye\n");
    return 0;
}

 

3. Write a program that asks the user to enter the number of days and then converts that value to weeks and days. For example, it would convert 18 days to 2 weeks, 4 days. Display results in the following format: 

18 days are 2 weeks, 4 days.

Use a while loop to allow the user to repeatedly enter day values; terminate the loop when the user enters a nonpositive value, such as 0 or -20.

#include <stdio.h>

int main(void) {
    const int daysperweek = 7;
    int days, weeks, day_rem;
    printf("Enter the number of days: ");
    scanf("%d", &days);
    while (days > 0) {
        weeks = days / daysperweek;
        day_rem = days % daysperweek;
        printf("%d days are %d weeks and %d days.\n", days, weeks, day_rem);
        printf("Enter the number of days (0 or less to end): ");

        scanf("%d", &days);
    }
    printf("Done!\n");
    return 0;
}

 


5. Write a program that requests a type double number and prints the value of the number cubed. Use a function of your own design to cube the value and print it. The main() program should pass the entered value to this function.

#include <stdio.h>

void showCube(double x);

int main(void) {
    double val;
    printf("Enter a floating-point value: ");
    scanf("%lf", &val);
    showCube(val);
    return 0;
}

void showCube(double x) {
    printf("The cube of %e is %e.\n", x, x * x * x);
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Preface Part I. The Basics 1. What Is C++? A Brief History of C++ C++ Organization How to Learn C++ 2. The Basics of Program Writing Programs from Conception to Execution Creating a Real Program Getting Help in Unix Getting Help in an IDE Programming Exercises 3. Style Comments C++ Code Naming Style Coding Religion Indentation and Code Format Clarity Simplicity Consistency and Organization Further Reading Summary 4. Basic Declarations and Expressions Basic Program Structure Simple Expressions The std::cout Output Object Variables and Storage Variable Declarations Assignment Statements Floating-Point Numbers Floating-Point Divide Versus Integer Divide Characters Wide Characters Boolean Type Programming Exercises Answers to Chapter Questions 5. Arrays, Qualifiers, and Reading Numbers Arrays Strings Reading Data Initializing Variables Multidimensional Arrays C-Style Strings Types of Integers Types of Floats Constant and Reference Declarations Qualifiers Hexadecimal and Octal Constants Operators for Performing Shortcuts Side Effects Programming Exercises Answers to Chapter Questions 6. Decision and Control Statements if Statement else Statement How Not to Use std::strcmp Looping Statements while Statement break Statement continue Statement The Assignment Anywhere Side Effect Programming Exercises Answers to Chapter Questions 7. The Programming Process Setting Up Your Work Area The Specification Code Design The Prototype The Makefile Testing Debugging Maintenance Revisions Electronic Archaeology Mark Up the Program Use the Debugger Use the Text Editor as a Browser Add Comments Programming Exercises Part II. Simple Programming 8. More Control Statements for Statement switch Statement switch, break, and continue Programming Exercises Answers to Chapter Questions 9. Variable Scope and Functions Scope and Storage Class Namespaces Functions Summary of Parameter Types Recursion Structured Programming Basics Real-World Programming Programming Exercises Answers to Chapter Questions 10. The C++ Preprocessor define Statement Conditional Compilation include Files Parameterized Macros Advanced Features Summary Programming Exercises Answers to Chapter Questions 11. Bit Operations Bit Operators The AND Operator (&) Bitwise OR (|) The Bitwise Exclusive OR (^) The Ones Complement Operator (NOT) (~) The Left and Right Shift Operators (>) Setting, Clearing, and Testing Bits Bitmapped Graphics Programming Exercises Answers to Chapter Questions Part III. Advanced Types and Classes 12. Advanced Types Structures Unions typedef enum Type Bit Members or Packed Structures Arrays of Structures Programming Exercises Answers to Chapter Questions 13. Simple Classes Stacks Improved Stack Using a Class Introduction to Constructors and Destructors Automatically Generated Member Functions Shortcuts Style Structures Versus Classes Programming Exercises 14. More on Classes Friends Constant Functions Constant Members Static Member Variables Static Member Functions The Meaning of static Programming Exercises 15. Simple Pointers const Pointers Pointers and Printing Pointers and Arrays The reinterpret_cast Pointers and Structures Command-Line Arguments Programming Exercises Answers to Chapter Questions Part IV. Advanced Programming Concepts 16. File Input/Output C++ File I/O Conversion Routines Binary and ASCII Files The End-of-Line Puzzle Binary I/O Buffering Problems Unbuffered I/O Designing File Formats C-Style I/O Routines C-Style Conversion Routines C-Style Binary I/O C- Versus C++- Style I/O Programming Exercises Answers to Chapter Questions 17. Debugging and Optimization Code Reviews Serial Debugging Going Through the Output Interactive Debuggers Debugging a Binary Search Interactive Debugging Tips and Tricks Runtime Errors Optimization How to Optimize Case Study: Inline Functions Versus Normal Functions Case Study: Optimizing a Color-Rendering Algorithm Programming Exercises Answers to Chapter Questions 18. Operator Overloading Creating a Simple Fixed-Point Class Operator Functions Operator Member Functions Warts Full Definition of the Fixed-Point Class Programming Exercises Answers to Chapter Questions 19. Floating Point Floating-Point Format Floating Addition/Subtraction Multiplication and Division Overflow and Underflow Roundoff Error Accuracy Minimizing Roundoff Error Determining Accuracy Precision and Speed Power Series Programming Exercises 20. Advanced Pointers Pointers, Structures, and Classes delete Operator Linked Lists Ordered Linked Lists Doubly Linked Lists Trees Printing a Tree The Rest of the Program Data Structures for a Chess Program Programming Exercises Answers to Chapter Questions 21. Advanced Classes Derived Classes Virtual Functions Virtual Classes Function Hiding in Derived Classes Constructors and Destructors in Derived Classes The dynamic_cast Operator Summary Programming Exercises Answers to Chapter Questions Part V. Other Language Features 22. Exceptions Adding Exceptions to the Stack Class Exceptions Versus assert Programming Exercises 23. Modular Programming Modules Public and Private The extern Storage Class Headers The Body of the Module A Program to Use Infinite Arrays The Makefile for Multiple Files Using the Infinite Array Dividing a Task into Modules Module Design Guidelines Programming Exercises 24. Templates What Is a Template? Templates: The Hard Way Templates: The C++ Way Function Specialization Class Templates Class Specialization Implementation Details Advanced Features Summary Programming Exercises 25. Standard Template Library STL Basics Class List-A Set of Students Creating a Waiting List with the STL List Storing Grades in a STL Map Putting It All Together Practical Considerations When Using the STL Getting More Information Exercises 26. Program Design Design Goals Design Factors Design Principles Coding Objects Real-World Design echniques Conclusion 27. Putting It All Together Requirements Code Design Coding Functional Description Testing Revisions A Final Warning Program Files Programming Exercises 28. From C to C++ K&R-Style Functions struct malloc and free Turning Structures into Classes setjmp and longjmp Mixing C and C++ Code Summary Programming Exercise 29. C++’s Dustier Corners do/while goto The ? : Construct The Comma Operator Overloading the ( ) Operator Pointers to Members The asm Statement The mutable Qualifier Run Time Type Identification Trigraphs Answers to Chapter Questions 30. Programming Adages General Design Declarations switch Statement Preprocessor Style Compiling The Ten Commandments for C++ Programmers Final Note Answers to Chapter Questions Part VI. Appendixes A. ASCII Table B. Ranges C. Operator Precedence Rules D. Computing Sine Using a Power Series E. Resources Index
You are visitor as of October 17, 1996.The Art of Assembly Language ProgrammingForward Why Would Anyone Learn This Stuff?1 What's Wrong With Assembly Language2 What's Right With Assembly Language?3 Organization of This Text and Pedagogical Concerns4 Obtaining Program Source Listings and Other Materials in This TextSection One: Machine OrganizationArt of Assembly Language: Chapter OneChapter One - Data Representation1.0 - Chapter Overview1.1 - Numbering Systems1.1.1 - A Review of the Decimal System1.1.2 - The Binary Numbering System1.1.3 - Binary Formats1.2 - Data Organization1.2.1 - Bits1.2.2 - Nibbles1.2.3 - Bytes1.2.4 - Words1.2.5 - Double Words1.3 - The Hexadecimal Numbering System1.4 - Arithmetic Operations on Binary and Hexadecimal Numbers1.5 - Logical Operations on Bits1.6 - Logical Operations on Binary Numbers and Bit Strings1.7 - Signed and Unsigned Numbers1.8 - Sign and Zero Extension1.9 - Shifts and Rotates1.10 - Bit Fields and Packed Data1.11 - The ASCII Character Set1.12 Summary1.13 Laboratory Exercises1.13.1 Installing the Software1.13.2 Data Conversion Exercises1.13.3 Logical Operations Exercises1.13.4 Sign and Zero Extension Exercises1.13.5 Packed Data Exercises1.14 Questions1.15 Programming ProjectsChapter Two - Boolean Algebra2.0 - Chapter Overview2.1 - Boolean Algebra2.2 - Boolean Functions and Truth Tables2.3 - Algebraic Manipulation of Boolean Expressions2.4 - Canonical Forms2.5 - Simplification of Boolean Functions2.6 - What Does This Have To Do With Computers, Anyway?2.6.1 - Correspondence Between Electronic Circuits and Boolean Functions2.6.2 - Combinatorial Circuits2.6.3 - Sequential and Clocked Logic2.7 - Okay, What Does It Have To Do With Programming, Then?2.8 - Generic Boolean Functions2.9 Laboratory Exercises<
Sams Teach Yourself C++ in 24 Hours is a hands-on guide to the C++ programming language. Readers are provided with short, practical examples that illustrate key concepts, syntax, and techniques. Using a straightforward approach, this fast and friendly tutorial teaches you everything you need to know, from installing and using a compiler, to debugging the programs you’ve created, to what’s new in C++14. Step-by-step instructions carefully walk you through the most common C++ programming tasks Quizzes and exercises at the end of each chapter help you test yourself to make sure you’re ready to go on Learn how to... Install and use a C++ compiler for Windows, Mac OS X, or Linux Build object-oriented programs in C++ Master core C++ concepts such as functions and classes Add rich functionality with templates and lambda expressions Debug your programs for flawless code Learn exception and error-handling techniques Put to use the new features in C++14, the latest version of the language Create and use templates Control program flow with loops Store information in arrays and strings Declare and use pointers Use operator overloading Extend classes with inheritance Use polymorphism and derived classes Employ object-oriented analysis and design Table of Contents Part I: Beginning C++ HOUR 1: Writing Your First Program HOUR 2: Organizing the Parts of a Program HOUR 3: Creating Variables and Constants HOUR 4: Using Expressions, Statements, and Operators HOUR 5: Calling Functions HOUR 6: Controlling the Flow of a Program HOUR 7: Storing Information in Arrays and Strings Part II: Classes HOUR 8: Creating Basic Classes HOUR 9: Moving into Advanced Classes Part III: Memory Management HOUR 10: Creating Pointers HOUR 11: Developing Advanced Pointers HOUR 12: Creating References HOUR 13: Developing Advanced References and Pointers Part IV: Advanced C++ HOUR 14: Calling Advanced Functions HOUR 15: Using Operator Overloading Part V: Inheritance and Polymorphism HOUR 16: Extending Classes with Inheritance HOUR 17: Using Polymorphism and Derived Classes HOUR 18: Making Use of Advanced Polymorphism Part VI: Special Topics HOUR 19: Storing Information in Linked Lists HOUR 20: Using Special Classes, Functions, and Pointers HOUR 21: Using New Features of C++14 HOUR 22: Employing Object-Oriented Analysis and Design HOUR 23: Creating Templates HOUR 24: Dealing with Exceptions and Error Handling Part VII: Appendixes APPENDIX A: Binary and Hexadecimal APPENDIX B: Glossary APPENDIX C: This Book’s Website APPENDIX D: Using the MinGW C++ Compiler on Windows
1 Computers and Programs 1 1.1 The Universal Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Program Power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 What is Computer Science? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.4 Hardware Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.5 Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.6 The Magic of Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.7 Inside a Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.8 Chaos and Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2 Writing Simple Programs 13 2.1 The Software Development Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.2 Example Program: Temperature Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.3 Elements of Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.3.1 Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.3.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.4 Output Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.5 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.5.1 Simple Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.5.2 Assigning Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.5.3 Simultaneous Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.6 Definite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 2.7 Example Program: Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 2.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 3 Computing with Numbers 25 3.1 Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.2 Using the Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3.3 Accumulating Results: Factorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.4 The Limits of Int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 3.5 Handling Large Numbers: Long Ints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.6 Type Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 3.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 4 Computing with Strings 39 4.1 The String Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 4.2 Simple String Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 4.3 Strings and Secret Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.3.1 String Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 4.3.2 Programming an Encoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 4.3.3 Programming a Decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4.3.4 Other String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 i ii CONTENTS 4.3.5 From Encoding to Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 4.4 Output as String Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 4.4.1 Converting Numbers to Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 4.4.2 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 4.4.3 Better Change Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4.5 File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.5.1 Multi-Line Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.5.2 File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.5.3 Example Program: Batch Usernames . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.5.4 Coming Attraction: Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 4.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 5 Objects and Graphics 61 5.1 The Object of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 5.2 Graphics Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 5.3 Using Graphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 5.4 Graphing Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 5.5 Choosing Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 5.6 Interactive Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.6.1 Getting Mouse Clicks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.6.2 Handling Textual Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 5.7 Graphics Module Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 5.7.1 GraphWin Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 5.7.2 Graphics Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 5.7.3 Entry Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 5.7.4 Displaying Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 5.7.5 Generating Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 5.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 6 Defining Functions 85 6.1 The Function of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 6.2 Functions, Informally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 6.3 Future Value with a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 6.4 Functions and Parameters: The Gory Details . . . . . . . . . . . . . . . . . . . . . . . . . . 90 6.5 Functions that Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 6.6 Functions and Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 6.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 7 Control Structures, Part 1 101 7.1 Simple Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 7.1.1 Example: TemperatureWarnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 7.1.2 Forming Simple Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 7.1.3 Example: Conditional Program Execution . . . . . . . . . . . . . . . . . . . . . . . 104 7.2 Two-Way Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 7.3 Multi-Way Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 7.4 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 7.5 Study in Design: Max of Three . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 7.5.1 Strategy 1: Compare Each to All . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 7.5.2 Strategy 2: Decision Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 7.5.3 Strategy 3: Sequential Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 7.5.4 Strategy 4: Use Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 7.5.5 Some Lessons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 7.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 CONTENTS iii 8 Control Structures, Part 2 119 8.1 For Loops: A Quick Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 8.2 Indefinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 8.3 Common Loop Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 8.3.1 Interactive Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 8.3.2 Sentinel Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 8.3.3 File Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 8.3.4 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 8.4 Computing with Booleans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 8.4.1 Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 8.4.2 Boolean Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 8.5 Other Common Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 8.5.1 Post-Test Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 8.5.2 Loop and a Half . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 8.5.3 Boolean Expressions as Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 8.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 9 Simulation and Design 137 9.1 Simulating Racquetball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 9.1.1 A Simulation Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 9.1.2 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 9.2 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 9.3 Top-Down Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 9.3.1 Top-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 9.3.2 Separation of Concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 9.3.3 Second-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 9.3.4 Designing simNGames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 9.3.5 Third-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 9.3.6 Finishing Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 9.3.7 Summary of the Design Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 9.4 Bottom-Up Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 9.4.1 Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 9.4.2 Simulation Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 9.5 Other Design Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 9.5.1 Prototyping and Spiral Development . . . . . . . . . . . . . . . . . . . . . . . . . . 150 9.5.2 The Art of Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 9.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 10 Defining Classes 155 10.1 Quick Review of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 10.2 Example Program: Cannonball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 10.2.1 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 10.2.2 Designing the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 10.2.3 Modularizing the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 10.3 Defining New Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 10.3.1 Example: Multi-Sided Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 10.3.2 Example: The Projectile Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 10.4 Objects and Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 10.4.1 Encapsulating Useful Abstractions . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 10.4.2 Putting Classes in Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 10.5 Widget Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 10.5.1 Example Program: Dice Roller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 10.5.2 Building Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 10.5.3 Building Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 iv CONTENTS 10.5.4 The Main Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 10.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 11 Data Collections 177 11.1 Example Problem: Simple Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 11.2 Applying Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 11.2.1 Lists are Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 11.2.2 Lists vs. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 11.2.3 List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 11.3 Statistics with Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 11.4 Combining Lists and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 11.5 Case Study: Python Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 11.5.1 A Calculator as an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 11.5.2 Constructing the Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 11.5.3 Processing Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 11.6 Non-Sequential Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 11.6.1 Dictionary Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 11.6.2 Dictionary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 11.6.3 Example Program: Word Frequency . . . . . . . . . . . . . . . . . . . . . . . . . . 194 11.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 12 Object-Oriented Design 201 12.1 The Process of OOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 12.2 Case Study: Racquetball Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 12.2.1 Candidate Objects and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 12.2.2 Implementing SimStats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 12.2.3 Implementing RBallGame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 12.2.4 Implementing Player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 12.2.5 The Complete Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 12.3 Case Study: Dice Poker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 12.3.1 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 12.3.2 Identifying Candidate Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 12.3.3 Implementing the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 12.3.4 A Text-Based UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 12.3.5 Developing a GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 12.4 OO Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 12.4.1 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 12.4.2 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 12.4.3 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 12.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 13 Algorithm Analysis and Design 225 13.1 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 13.1.1 A Simple Searching Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 13.1.2 Strategy 1: Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 13.1.3 Strategy 2: Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 13.1.4 Comparing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 13.2 Recursive Problem-Solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228 13.2.1 Recursive Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 13.2.2 Recursive Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 13.2.3 Recursive Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 13.3 Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 13.3.1 Naive Sorting: Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 13.3.2 Divide and Conquer: Merge Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 CONTENTS v 13.3.3 Comparing Sorts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 13.4 Hard Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 13.4.1 Towers of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 13.4.2 The Halting Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 13.4.3 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Your hands-on guide to Visual C# fundamentals Expand your expertise—and teach yourself the fundamentals of Microsoft Visual C# 2013. If you have previous programming experience but are new to Visual C# 2013, this tutorial delivers the step-by-step guidance and coding exercises you need to master corMIcrosoft Microsoft visual c# 2013 Step by step John Sharp Published with the authorization of Microsoft Corporation by O'Reilly media, Inc 1005 Gravenstein Highway North Sebastopol, California 95472 Copyright@ 2013 by John Sharp All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher. SBN:978-0-7356-8183-5 123456789LS|876543 Printed and bound in the united states of america Microsoft Press books are available through booksellers and distributors worldwide. If you need support related tothisbook,emailMicrosoftPressBookSupportatmspinput@microsoft.com.Pleasetelluswhatyouthinkof thisbookathttp://www.microsoft.com/learning/booksurvey. Microsoftandthetrademarkslistedathttp.://www.microsoft.com/about/legal/en/us/intellectualproperty/ Trademarks/ EN-US. aspx are trademarks of the microsoft group of companies. All other marks are property of their respective owners The example companies, organizations, products, domain names, email addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, email address, logo, person, place, or event is intended or should be inferred This book expresses the authors views and opinions. The information contained in this book is provided without any express, statutory, or implied warranties. Neither the authors, O'Reilly Media, Inc, Microsoft Corporation. nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directl or indirectly by this book Acquisitions and Developmental Editor: russell Jones Production Editor: Christopher Hearse Technical reviewer. John mueller Copyeditor: Octal Publishing, Inc Indexer: Ellen troutman Cover Design: Twist Creative. Seattle Cover Composition: Ellie Volckhausen Illustrator: Rebecca Demarest Contents at a glance Introduction ⅩX ART I INTRODUCING MICROSOFT VISUAL C# AND MICROSOFT VISUAL STUDIO 2013 HAPTER 1 Welcome to c# CHAPTER 2 Working with variables, operators, and expressions 39 ChaPTER 3 Writing methods and applying scope 65 CHAPTER 4 Using decision statements 93 CHAPTER 5 Using compound assignment and iteration statements 113 CHAPTER 6 Managing errors and exceptions 135 PART II UNDERSTANDING THE C# OBJECT MODEL CHAPTER 7 Creating and managing classes and objects 161 ChAPTeR 8 Understanding values and references 183 CHAPTER 9 Creating value types with enumerations and structures 207 CHAPTER 10 Using arrays 227 CHAPTER 11 Understanding parameter arrays 251 CHAPTER 12 Working with inheritance 263 CHAPTER 13 Creating interfaces and defining abstract classes 287 CHAPTER 14 Using garbage collection and resource management 317 PARTⅢ DEFINING EXTENSIBLE TYPES WITH C# CHAPTER 15 Implementing properties to access fields 341 CHAPTER 16 Using indexers 363 CHAPTER 17 ntroducing generic 381 CHAPTER 18 Using collections 411 CHAPTER 19 Enumerating collections 435 CHAPTER 20 Decoupling application logic and handling events 451 CHAPTER 21 Querying in-memory data by using query expressions 485 CHAPTER 22 Operator overloading 511 PART IV BUILDING PROFESSIONAL WINDOWS 8.1 APPLICATIONS WITH C# CHAPTER 23 Improving throughput by using tasks 537 CHAPTER 24 Improving response time by performing asynchronous operations 581 CHAPTER 25 Implementing the user interface for a Windows Store app 623 CHAPTER 26 isplaying and searching for data in a windows Store app 673 CHAPTER 27 Accessing a remote database from a Windows Store app 721 Index 763 Contents at a glance Contents ,ⅩX PART INTRODUCING MICROSOFT VISUAL C# AND MICROSOFT VISUAL STUDIO 2013 Chapter 1 Welcome to C# 3 Beginning programming with the Visual Studio 2013 environment Writing your first program Using namespaces 14 Creating a graphical applicatio 18 Examining the Windows Store app 30 Examining the WPF application Adding code to the graphical application 34 Summary 38 Quick Reference 38 Chapter 2 Working with variables, operators, and expressions 39 Understanding statements Using identifiers 40 Identifying keywords 40 Using variables Naming variables Declaring variables Working with primitive data types Unassigned local variables 43 Displaying primitive data type values 44 What do you think of this book? We want to hear from you! Microsoft is interested in hearing your feed back so we can continually improve our books and learning resources for you To participate in a brief online survey please visit: www.microsoft.com/learning/booksurvey/ ing arithmetic operators 52 d perators and typ es Examining arithmetic operators Controlling precedence Using associativity to evaluate expressions ..60 Associativity and the assignment operator 60 Incrementing and decrementing variables 61 Prefix and postfix 61 Declaring implicitly typed local variables 62 Summary 63 Quick Refer 64 Chapter 3 Writing methods and applying scope 65 Creating methods 65 Declaring a method .66 Returning data from a method 67 Calling methods 69 Applying scope 72 Defining local scope 72 Defining class scope 73 Overloading methods 74 Writing methods Using optional parameters and named arguments 83 Defining optional parameters 85 Passing named arguments 85 Resolving ambiguities with optional parameters and named arguments 86 Summa 91 Quick referer 92 Chapter 4 Using decision statements 93 Declaring boolean variables .93 sing boolean operators 94 Contents Understanding equality and relational operators Understanding conditional logical operators .95 Short-circuiting Summarizing operator precedence and associativity 66 Using if statements to make decisions ..97 Understanding if statement syntax Using blocks to group statements 98 Cascading if statements 99 Using switch statement 105 Understanding switch statement syntax 106 Following the switch statement rules 107 Summary 111 Quick reference ....111 Chapter 5 Using compound assignment and iteration statements 113 Using compound assignment operators 113 Writing while statements 115 Writing for Statements Understanding for statement scope 123 Writing do stateme 123 ummar 132 Quick reference 133 Chapter 6 Managing errors and exceptions 135 Coping with errors 135 Trying code and catching exceptions .136 handled Excepti 137 Using multiple catch 138 Catching multiple exceptions 139 Propagating exceptions 145 Using checked and unchecked integer arithmetic 147 Writing checked statements 148 Contents Writing checked expressions 149 Throwing exceptions 152 Using a finally block 156 ummar 158 Quick reference 158 PART UNDERSTANDING THE C# OBJECT MODEL Chapter 7 Creating and managing classes and objects 161 Understanding classification 161 The purpose of encapsulation ....162 Defining and using a class 162 Controlling accessibility 164 Working with constructors 165 Overloading constructors 167 Understanding static methods and data 175 Creating a shared field 176 Creating a static field by using the const keyword 177 Understanding static classes 177 Anonymous classes ...180 Summary .........181 Quick reference 182 Chapter 8 Understanding values and references 183 Copying value type variables and classes ....183 Understanding null values and nullable types 189 Using nullable type 190 Understanding the properties of nullable types .191 Using ref and out parameters .192 Creating ref parameters 193 Creating out parameters .193 How computer memory is organized 195 Using the stack and the heap 197 vu Contents
Java How to Program (Late Objects), Tenth Edition is intended for use in the Java programming course. It also serves as a useful reference and self-study tutorial to Java programming. The Deitels’ groundbreaking How to Program series offers unparalleled breadth and depth of object-oriented programming concepts and intermediate-level topics for further study. Java How to Program (Late Objects), Tenth Edition, teaches programming by presenting the concepts in the context of full working programs. The Late Objects Version delays coverage of class development, first presenting control structures, methods and arrays material in a non-object-oriented, procedural programming context. Teaching and Learning Experience This program presents a better teaching and learning experience—for you and your students. Teach Programming with the Deitels’ Signature Live Code Approach: Java language features are introduced with thousands of lines of code in hundreds of complete working programs. Use a Late Objects Approach: The Late Objects Version begins with a rich treatment of procedural programming, including two full chapters on control statements and 200+ exercises. Keep Your Course Current: This edition can be used with Java SE 7 or Java SE 8, and is up-to-date with the latest technologies and advancements. Facilitate Learning with Outstanding Applied Pedagogy: Making a Difference exercise sets, projects, and hundreds of valuable programming tips help students apply concepts. Support Instructors and Students: Student and instructor resources are available to expand on the topics presented in the text. Table of Contents Chapter 1 Introduction to Computers, the Internet and Java Chapter 2 Introduction to Java Applications; Input/Output and Operators Chapter 3 Control Statements: Part 1; Assignment, ++ and -- Operators Chapter 4 Control Statements: Part 2; Logical Operators Chapter 5 Methods Chapter 6 Arrays and ArrayLists Chapter 7 Introduction to Classes and Objects Chapter 8
xvii Contents Finishing Your Modules 154 Defining Module-Specific Errors 154 Choosing What to Export 155 Documenting Your Modules 156 Try It Out: Viewing Module Documentation 157 Testing Your Module 162 Running a Module as a Program 164 Try It Out: Running a Module 164 Creating a Whole Module 165 Try It Out: Finishing a Module 165 Try It Out: Smashing Imports 169 Installing Your Modules 170 Try It Out: Creating an Installable Package 171 Summary 174 Exercises 174 Chapter 11: Text Processing 175 Why Text Processing Is So Useful 175 Searching for Files 176 Clipping Logs 177 Sifting through Mail 178 Navigating the File System with the os Module 178 Try It Out: Listing Files and Playing with Paths 180 Try It Out: Searching for Files of a Particular Type 181 Try It Out: Refining a Search 183 Working with Regular Expressions and the re Module 184 Try It Out: Fun with Regular Expressions 186 Try It Out: Adding Tests 187 Summary 189 Exercises 189 Chapter 12: Testing 191 Assertions 191 Try It Out: Using Assert 192 Test Cases and Test Suites 193 Try It Out: Testing Addition 194 Try It Out: Testing Faulty Addition 195 Test Fixtures 196 Try It Out: Working with Test Fixtures 197 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xvii xviii Contents Putting It All Together with Extreme Programming 199 Implementing a Search Utility in Python 200 Try It Out: Writing a Test Suite First 201 Try It Out: A General-Purpose Search Framework 203 A More Powerful Python Search 205 Try It Out: Extending the Search Framework 206 Formal Testing in the Software Life Cycle 207 Summary 208 Chapter 13: Writing a GUI with Python 209 GUI Programming Toolkits for Python 209 PyGTK Introduction 210 pyGTK Resources 211 Creating GUI Widgets with pyGTK 213 Try It Out: Writing a Simple pyGTK Program 213 GUI Signals 214 GUI Helper Threads and the GUI Event Queue 216 Try It Out: Writing a Multithreaded pyGTK App 219 Widget Packing 222 Glade: a GUI Builder for pyGTK 223 GUI Builders for Other GUI Frameworks 224 Using libGlade with Python 225 A Glade Walkthrough 225 Starting Glade 226 Creating a Project 227 Using the Palette to Create a Window 227 Putting Widgets into the Window 228 Glade Creates an XML Representation of the GUI 230 Try It Out: Building a GUI from a Glade File 231 Creating a Real Glade Application 231 Advanced Widgets 238 Further Enhancing PyRAP 241 Summary 248 Exercises 248 Chapter 14: Accessing Databases 249 Working with DBM Persistent Dictionaries 250 Choosing a DBM Module 250 Creating Persistent Dictionaries 251 Try It Out: Creating a Persistent Dictionary 251 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xviii xix Contents Accessing Persistent Dictionaries 252 Try It Out: Accessing Persistent Dictionaries 253 Deciding When to Use DBM and When to Use a Relational Database 255 Working with Relational Databases 255 Writing SQL Statements 257 Defining Tables 259 Setting Up a Database 260 Try It Out: Creating a Gadfly Database 261 Using the Python Database APIs 262 Downloading Modules 263 Creating Connections 263 Working with Cursors 264 Try It Out: Inserting Records 264 Try It Out: Writing a Simple Query 266 Try It Out: Writing a Complex Join 267 Try It Out: Updating an Employee’s Manager 269 Try It Out: Removing Employees 270 Working with Transactions and Committing the Results 271 Examining Module Capabilities and Metadata 272 Handling Errors 272 Summary 273 Exercises 274 Chapter 15: Using Python for XML 275 What Is XML? 275 A Hierarchical Markup Language 275 A Family of Standards 277 What Is a Schema/DTD? 278 What Are Document Models For? 278 Do You Need One? 278 Document Type Definitions 278 An Example DTD 278 DTDs Aren’t Exactly XML 280 Limitations of DTDs 280 Schemas 280 An Example Schema 280 Schemas Are Pure XML 281 Schemas Are Hierarchical 281 Other Advantages of Schemas 281 Schemas Are Less Widely Supported 281 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xix xx Contents XPath 282 HTML as a Subset of XML 282 The HTML DTDs 283 HTMLParser 283 Try It Out: Using HTMLParser 283 htmllib 284 Try It Out: Using htmllib 284 XML Libraries Available for Python 285 Validating XML Using Python 285 What Is Validation? 286 Well-Formedness versus Validation 286 Available Tools 286 Try It Out: Validation Using xmlproc 286 What Is SAX? 287 Stream-based 288 Event-driven 288 What Is DOM? 288 In-memory Access 288 Why Use SAX or DOM 289 Capability Trade-Offs 289 Memory Considerations 289 Speed Considerations 289 SAX and DOM Parsers Available for Python 289 PyXML 290 xml.sax 290 xml.dom.minidom 290 Try It Out: Working with XML Using DOM 290 Try It Out: Working with XML Using SAX 292 Intro to XSLT 293 XSLT Is XML 293 Transformation and Formatting Language 293 Functional,Template-Driven 293 Using Python to Transform XML Using XSLT 294 Try It Out: Transforming XML with XSLT 294 Putting It All Together: Working with RSS 296 RSS Overview and Vocabulary 296 Making Sense of It All 296 RSS Vocabulary 297 An RSS DTD 297 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xx xxi Contents A Real-World Problem 297 Try It Out: Creating an RSS Feed 298 Creating the Document 300 Checking It Against the DTD 301 Another Real-World Problem 301 Try It Out: Creating An Aggregator 301 Summary 303 Exercises 303 Chapter 16: Network Programming 305 Try It Out: Sending Some E-mail 305 Understanding Protocols 307 Comparing Protocols and Programming Languages 307 The Internet Protocol Stack 308 A Little Bit About the Internet Protocol 309 Internet Addresses 309 Internet Ports 310 Sending Internet E-mail 311 The E-mail File Format 311 MIME Messages 313 MIME Encodings: Quoted-printable and Base64 313 MIME Content Types 314 Try It Out: Creating a MIME Message with an Attachment 315 MIME Multipart Messages 316 Try It Out: Building E-mail Messages with SmartMessage 320 Sending Mail with SMTP and smtplib 321 Try It Out: Sending Mail with MailServer 323 Retrieving Internet E-mail 323 Parsing a Local Mail Spool with mailbox 323 Try It Out: Printing a Summary of Your Mailbox 324 Fetching Mail from a POP3 Server with poplib 325 Try It Out: Printing a Summary of Your POP3 Mailbox 327 Fetching Mail from an IMAP Server with imaplib 327 Try It Out: Printing a Summary of Your IMAP Mailbox 329 IMAP’s Unique Message IDs 330 Try It Out: Fetching a Message by Unique ID 330 Secure POP3 and IMAP 331 Webmail Applications Are Not E-mail Applications 331 Socket Programming 331 Introduction to Sockets 332 Try It Out: Connecting to the SuperSimpleSocketServer with Telnet 333 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xxi xxii Contents Binding to an External Hostname 334 The Mirror Server 335 Try It Out: Mirroring Text with the MirrorServer 336 The Mirror Client 336 SocketServer 337 Multithreaded Servers 339 The Python Chat Server 340 Design of the Python Chat Server 340 The Python Chat Server Protocol 341 Our Hypothetical Protocol in Action 341 Initial Connection 342 Chat Text 342 Server Commands 342 General Guidelines 343 The Python Chat Client 346 Single-Threaded Multitasking with select 348 Other Topics 350 Miscellaneous Considerations for Protocol Design 350 Trusted Servers 350 Terse Protocols 350 The Twisted Framework 351 Deferred Objects 351 The Peer-to-Peer Architecture 354 Summary 354 Exercises 354 Chapter 17: Extension Programming with C 355 Extension Module Outline 356 Building and Installing Extension Modules 358 Passing Parameters from Python to C 360 Returning Values from C to Python 363 The LAME Project 364 The LAME Extension Module 368 Using Python Objects from C Code 380 Summary 383 Exercises 383 Chapter 18: Writing Shareware and Commercial Programs 385 A Case Study: Background 385 How Much Python Should You Use? 386 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xxii xxiii Contents Pure Python Licensing 387 Web Services Are Your Friend 388 Pricing Strategies 389 Watermarking 390 Other Models 394 Selling as a Platform,Rather Than a Product 395 Your Development Environment 395 Finding Python Programmers 396 Training non-Python Programmers 397 Python Employment Resources 397 Python Problems 397 Porting to Other Versions of Python 397 Porting to Other Operating Systems 398 Debugging Threads 399 Common Gotchas 399 Portable Distribution 400 Essential Libraries 401 Timeoutsocket 401 PyGTK 402 GEOip 402 Summary 403 Chapter 19: Numerical Programming 405 Numbers in Python 405 Integers 406 Long Integers 406 Floating-point Numbers 407 Formatting Numbers 408 Characters as Numbers 410 Mathematics 412 Arithmetic 412 Built-in Math Functions 414 The math Module 415 Complex Numbers 416 Arrays 418 The array Module 420 The numarray Package 422 Using Arrays 422 Computing the Standard Deviation 423 Summary 424 Exercises 425 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xxiii xxiv Contents Chapter 20: Python in the Enterprise 427 Enterprise Applications 428 Document Management 428 The Evolution of Document Management Systems 429 What You Want in a Document Management System 430 People in Directories 431 Taking Action with Workflow 432 Auditing,Sarbanes-Oxley,and What You Need to Know 433 Auditing and Document Management 434 Working with Actual Enterprise Systems 435 Introducing the wftk Workflow Toolkit 435 Try It Out: Very Simple Record Retrieval 436 Try It Out: Very Simple Record Storage 438 Try It Out: Data Storage in MySQL 439 Try It Out: Storing and Retrieving Documents 441 Try It Out: A Document Retention Framework 446 The python-ldap Module 448 Try It Out: Using Basic OpenLDAP Tools 449 Try It Out: Simple LDAP Search 451 More LDAP 453 Back to the wftk 453 Try It Out: Simple Workflow Trigger 454 Try It Out: Action Queue Handler 456 Summary 458 Exercises 458 Chapter 21: Web Applications and Web Services 459 REST: The Architecture of the Web 460 Characteristics of REST 460 A Distributed Network of Interlinked Documents 461 A Client-Server Architecture 461 Servers Are Stateless 461 Resources 461 Representations 462 REST Operations 462 HTTP: Real-World REST 463 Try It Out: Python’s Three-Line Web Server 463 The Visible Web Server 464 Try It Out: Seeing an HTTP Request and Response 465 The HTTP Request 466 The HTTP Response 467 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xxiv xxv Contents CGI: Turning Scripts into Web Applications 468 Try It Out: Running a CGI Script 469 The Web Server Makes a Deal with the CGI Script 470 CGI’s Special Environment Variables 471 Accepting User Input through HTML Forms 473 The cgi Module: Parsing HTML Forms 474 Try It Out: Printing Any HTML Form Submission 478 Building a Wiki 480 The BittyWiki Core Library 481 Back-end Storage 481 WikiWords 481 Writing the BittyWiki Core 481 Try It Out: Creating Wiki Pages from an Interactive Python Session 483 The BittyWiki Web Interface 484 Resources 484 Request Structure 484 But Wait—There’s More (Resources) 485 Wiki Markup 486 Web Services 493 How Web Services Work 494 REST Web Services 494 REST Quick Start: Finding Bargains on Amazon.com 495 Try It Out: Peeking at an Amazon Web Services Response 496 Introducing WishListBargainFinder 497 Giving BittyWiki a REST API 500 Wiki Search-and-Replace Using the REST Web Service 503 Try It Out: Wiki Searching and Replacing 507 XML-RPC 508 XML-RPC Quick Start: Get Tech News from Meerkat 509 The XML-RPC Request 511 Representation of Data in XML-RPC 512 The XML-RPC Response 513 If Something Goes Wrong 513 Exposing the BittyWiki API through XML-RPC 514 Try It Out: Manipulating BittyWiki through XML-RPC 517 Wiki Search-and-Replace Using the XML-RPC Web Service 518 SOAP 520 SOAP Quick Start: Surfing the Google API 520 The SOAP Request 522 The SOAP Response 524 If Something Goes Wrong 524 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xxv xxvi Contents Exposing a SOAP Interface to BittyWiki 525 Try It Out: Manipulating BittyWiki through SOAP 526 Wiki Search-and-Replace Using the SOAP Web Service 527 Documenting Your Web Service API 529 Human-Readable API Documentation 529 The BittyWiki REST API Document 529 The BittyWiki XML-RPC API Document 529 The BittyWiki SOAP API Document 530 The XML-RPC Introspection API 530 Try It Out: Using the XML-RPC Introspection API 530 WSDL 531 Try It Out: Manipulating BittyWiki through a WSDL Proxy 533 Choosing a Web Service Standard 534 Web Service Etiquette 535 For Consumers of Web Services 535 For Producers of Web Services 535 Using Web Applications as Web Services 536 A Sampling of Publicly Available Web Services 536 Summary 538 Exercises 538 Chapter 22: Integrating Java with Python 539 Scripting within Java Applications 540 Comparing Python Implementations 541 Installing Jython 541 Running Jython 542 Running Jython Interactively 542 Try It Out: Running the Jython Interpreter 542 Running Jython Scripts 543 Try It Out Running a Python Script 543 Controlling the jython Script 544 Making Executable Commands 545 Try It Out: Making an Executable Script 546 Running Jython on Your Own 546 Packaging Jython-Based Applications 547 Integrating Java and Jython 547 Using Java Classes in Jython 548 Try It Out: Calling on Java Classes 548 Try It Out: Creating a User Interface from Jython 550 Accessing Databases from Jython 552 Working with the Python DB API 553 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xxvi xxvii Contents Setting Up a Database 554 Try It Out: Create Tables 555 Writing J2EE Servlets in Jython 558 Setting Up an Application Server 559 Adding the PyServlet to an Application Server 560 Extending HttpServlet 561 Try It Out: Writing a Python Servlet 562 Choosing Tools for Jython 564 Testing from Jython 565 Try It Out: Exploring Your Environment with Jython 565 Embedding the Jython Interpreter 566 Calling Jython Scripts from Java 566 Try It Out: Embedding Jython 567 Compiling Python Code to Java 568 Handling Differences between C Python and Jython 569 Summary 570 Exercises 571 Appendix A: Answers to Exercises 573 Appendix B: Online Resources 605 Appendix C: What’s New in Python 2.4 609 Glossary 613 Index 623 Contents Acknowledgments xxix Introduction xxxi Chapter 1: Programming Basics and Strings 1 How Programming Is Different from Using a Computer 1 Programming Is Consistency 2 Programming Is Control 2 Programming Copes with Change 2 What All That Means Together 3 The First Steps 3 Starting codeEditor 3 Using codeEditor’s Python Shell 4 Try It Out: Starting the Python Shell 4 Beginning to Use Python—Strings 5 What Is a String? 5 Why the Quotes? 6 Try It Out: Entering Strings with Different Quotes 6 Understanding Different Quotes 6 Putting Two Strings Together 8 Try It Out: Using + to Combine Strings 8 Putting Strings Together in Different Ways 9 Try It Out: Using a Format Specifier to Populate a String 9 Try It Out: More String Formatting 9 Displaying Strings with Print 10 Try It Out: Printing Text with Print 10 Summary 10 Exercises 11 Chapter 2: Numbers and Operators 13 Different Kinds of Numbers 13 Numbers in Python 14 Try It Out: Using Type with Different Numbers 14 Try It Out: Creating an Imaginary Number 15 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xi xii Contents Program Files 15 Try It Out: Using the Shell with the Editor 16 Using the Different Types 17 Try It Out Including Different Numbers in Strings 18 Try It Out: Escaping the % Sign in Strings 18 Basic Math 19 Try It Out Doing Basic Math 19 Try It Out: Using the Modulus Operation 20 Some Surprises 20 Try It Out: Printing the Results 21 Using Numbers 21 Order of Evaluation 21 Try It Out: Using Math Operations 21 Number Formats 22 Try It Out: Using Number Formats 22 Mistakes Will Happen 23 Try It Out: Making Mistakes 23 Some Unusual Cases 24 Try It Out: Formatting Numbers as Octal and Hexadecimal 24 Summary 24 Exercises 25 Chapter 3: Variables—Names for Values 27 Referring to Data – Using Names for Data 27 Try It Out: Assigning Values to Names 28 Changing Data Through Names 28 Try It Out: Altering Named Values 29 Copying Data 29 Names You Can’t Use and Some Rules 29 Using More Built-in Types 30 Tuples—Unchanging Sequences of Data 30 Try It Out: Creating and Using a Tuple 30 Try It Out: Accessing a Tuple Through Another Tuple 31 Lists—Changeable Sequences of Data 33 Try It Out Viewing the Elements of a List 33 Dictionaries—Groupings of Data Indexed by Name 34 Try It Out: Making a Dictionary 34 Try It Out: Getting the Keys from a Dictionary 35 Treating a String Like a List 36 Special Types 38 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xii xiii Contents Other Common Sequence Properties 38 Referencing the Last Elements 38 Ranges of Sequences 39 Try It Out: Slicing Sequences 39 Growing Lists by Appending Sequences 40 Using Lists to Temporarily Store Data 40 Try It Out: Popping Elements from a List 40 Summary 41 Exercises 42 Chapter 4: Making Decisions 43 Comparing Values—Are They the Same? 43 Try It Out: Comparing Values for Sameness 43 Doing the Opposite—Not Equal 45 Try It Out: Comparing Values for Difference 45 Comparing Values—Which One Is More? 45 Try It Out: Comparing Greater Than and Less Than 45 More Than or Equal,Less Than or Equal 47 Reversing True and False 47 Try It Out: Reversing the Outcome of a Test 47 Looking for the Results of More Than One Comparison 48 How to Get Decisions Made 48 Try It Out: Placing Tests within Tests 49 Repetition 51 How to Do Something—Again and Again 51 Try It Out: Using a while Loop 51 Stopping the Repetition 52 Try It Out: Using else While Repeating 54 Try It Out: Using continue to Keep Repeating 54 Handling Errors 55 Trying Things Out 55 Try It Out: Creating an Exception with Its Explanation 56 Summary 57 Exercises 58 Chapter 5: Functions 59 Putting Your Program into Its Own File 59 Try It Out: Run a Program with Python -i 61 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xiii xiv Contents Functions: Grouping Code under a Name 61 Try It Out: Defining a Function 61 Choosing a Name 62 Describing a Function in the Function 63 Try It Out: Displaying __doc__ 63 The Same Name in Two Different Places 64 Making Notes to Yourself 65 Try It Out: Experimenting with Comments 65 Asking a Function to Use a Value You Provide 66 Try It Out Invoking a Function with Parameters 67 Checking Your Parameters 68 Try It Out: Determining More Types with the type Function 69 Try It Out: Using Strings to Compare Types 69 Setting a Default Value for a Parameter—Just in Case 70 Try It Out: Setting a Default Parameter 70 Calling Functions from within Other Functions 71 Try It Out: Invoking the Completed Function 72 Functions Inside of Functions 72 Flagging an Error on Your Own Terms 73 Layers of Functions 74 How to Read Deeper Errors 74 Summary 75 Exercises 76 Chapter 6: Classes and Objects 79 Thinking About Programming 79 Objects You Already Know 79 Looking Ahead: How You Want to Use Objects 81 Defining a Class 81 How Code Can Be Made into an Object 81 Try It Out: Defining a Class 82 Try It Out: Creating an Object from Your Class 82 Try It Out: Writing an Internal Method 84 Try It Out: Writing Interface Methods 85 Try It Out: Using More Methods 87 Objects and Their Scope 89 Try It Out: Creating Another Class 89 Summary 92 Exercises 93 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xiv xv Contents Chapter 7: Organizing Programs 95 Modules 96 Importing a Module So That You Can Use It 96 Making a Module from Pre-existing Code 97 Try It Out: Creating a Module 97 Try It Out: Exploring Your New Module 98 Using Modules—Starting With the Command Line 99 Try It Out: Printing sys.argv 100 Changing How Import Works—Bringing in More 101 Packages 101 Try It Out: Making the Files in the Kitchen Class 102 Modules and Packages 103 Bringing Everything into the Current Scope 103 Try It Out: Exporting Modules from a Package 104 Re-importing Modules and Packages 104 Try It Out: Examining sys.modules 105 Basics of Testing Your Modules and Packages 106 Summary 106 Exercises 107 Chapter 8: Files and Directories 109 File Objects 109 Writing Text Files 110 Reading Text Files 111 Try It Out: Printing the Lengths of Lines in the Sample File 112 File Exceptions 113 Paths and Directories 113 Paths 114 Directory Contents 116 Try It Out: Getting the Contents of a Directory 116 Try It Out: Listing the Contents of Your Desktop or Home Directory 118 Obtaining Information about Files 118 Recursive Directory Listings 118 Renaming,Moving,Copying,and Removing Files 119 Example: Rotating Files 120 Creating and Removing Directories 121 Globbing 122 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xv xvi Contents Pickles 123 Try It Out: Creating a Pickle File 123 Pickling Tips 124 Efficient Pickling 125 Summary 125 Exercises 125 Chapter 9: Other Features of the Language 127 Lambda and Filter: Short Anonymous Functions 127 Reduce 128 Try It Out: Working with Reduce 128 Map: Short-Circuiting Loops 129 Try It Out: Use Map 129 Decisions within Lists—List Comprehension 130 Generating Lists for Loops 131 Try It Out: Examining an xrange Object 132 Special String Substitution Using Dictionaries 133 Try It Out: String Formatting with Dictionaries 133 Featured Modules 134 Getopt—Getting Options from the Command Line 134 Using More Than One Process 137 Threads—Doing Many Things in the Same Process 139 Storing Passwords 140 Summary 141 Exercises 142 Chapter 10: Building a Module 143 Exploring Modules 143 Importing Modules 145 Finding Modules 145 Digging through Modules 146 Creating Modules and Packages 150 Try It Out: Creating a Module with Functions 150 Working with Classes 151 Defining Object-Oriented Programming 151 Creating Classes 151 Try It Out: Creating a Meal Class 152 Extending Existing Classes 153 02_596543 ftoc.qxd 6/29/05 10:55 PM Page xvi
Editorial Reviews Stay ahead of the game with this comprehensive guide to the C# programming language Well-known C# expert Rod Stephens gives novice and experienced developers a comprehensive tutorial and reference to standard C#. This new title fully covers the latest C# language standard, C# 5.0, as well as its implementation in the 2013 release of Visual Studio. The author provides exercises and solutions; and his C# Helper website will provide readers and students with ongoing support. This resource is packed with tips, tricks, tutorials, examples, and exercises and is the perfect professional companion for programmers who want to stay ahead of the game. Author Rod Stephens is a well-known programming authority and has written more than 25 programming books covering C#, Java, VB, and other languages. His books have sold more than 60,000 copies in multiple editions. This book’s useful exercises and solutions are designed to support training and higher education adoptions. Learn the full range of C# programming language features Quickly locate information for specific language features in the reference section Familiarize yourself with handling data types, variables, constants, and much more Experiment with editing and debugging code and using LINQ Beginning through intermediate-level programmers will benefit from the accessible style of C# 5.0 Programmer’s Reference and will have access to its comprehensive range of more advanced topics. Additional support and complementary material are provided at the C# Helper website, www.csharphelper.com. Stay up-to-date and improve your programming skills with this invaluable resource. Table of Contents Part I: The C# Ecosystem Chapter 1: The C# Environment Chapter 2: Writing a First Program Chapter 3: Program and Code File Structure Part II: C# Language Elements Chapter 4: Data Types, Variables, and Constants Chapter 5: Operators Chapter 6: Methods Chapter 7: Program Control Statements Chapter 8: LINQ Chapter 9: Error Handling Chapter 10: Tracing and Debugging Part III: Object-Oriented Programming Chapter 11: OOP Concepts Chapter 12: Classes and Structures Chapter 13: Namespaces Chapter 14: Collection Classes Chapter 15: Generics Part IV: Interacting with the Environment Chapter 16: Printing Chapter 17: Configuration and Resources Chapter 18: Streams Chapter 19: File System Objects Chapter 20: Networking Part V: Advanced Topics Chapter 21: Regular Expressions Chapter 22: Parallel Programming Chapter 23: ADO.NET Chapter 24: XML Chapter 25: Serialization Chapter 26: Reflection Chapter 27: Cryptography Part VI: Appendices Appendix A: Solutions to Exercises Appendix B: Data Types Appendix C: Variable Declarations Appendix D: Constant Declarations Appendix E: Operators Appendix F: Method Declarations Appendix G: Useful Attributes Appendix H: Control Statements Appendix I: Error Handling Appendix J: LINQ Appendix K: Classes and Structures Appendix L: Collection Classes Appendix M: Generic Declarations Appendix N: Printing and Graphics Appendix O: Useful Exception Classes Appendix P: Date and Time Format Specifiers Appendix Q: Other Format Specifiers Appendix R: Streams Appendix S: Filesystem Classes Appendix T: Regular Expressions Appendix U: Parallel Programming Appendix V: XML Appendix W: Serialization Appendix X: Reflection Book Details Title: C# 5.0 Programmer’s Reference Author: Rod Stephens Length: 960 pages Edition: 1 Language: English Publisher: Wrox Publication Date: 2014-04-28 ISBN-10: 1118847288 ISBN-13: 9781118847282

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九成宫醴泉铭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值