Fundamentals of computer programming with CSharp nakov ebook v2013

1.1K 2.7K 0
Fundamentals of computer programming with CSharp nakov ebook v2013

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp lập trình c, lập trình c sharp

Fundamentals of Computer Programming with C# (The Bulgarian C# Programming Book) by Svetlin Nakov & Co http://www.introprogramming.info ISBN: 978-954-400-773-7 ISBN-13: 978-954-400-773-7 (9789544007737) ISBN-10: 954-400-773-3 (9544007733) Pages: 1122 Language: English Published: Sofia, 2013 Tags: book; free book; ebook; e-book; programming; computer programming; programming concepts; programming principles; tutorial; C#; data structures; algorithms; Intro C#; C# book; book C#; CSharp; CSharp book; programming book; book programming; textbook; learn C#; study C#; learn programming; study programming; how to program; programmer; practical programming guide; software engineer; software engineering; computer programming; software developer; software technologies; programming techniques; logi cal thinking; algorithmic thinking; developer; software development; programming knowledge; programming skills; programming language; basics of programming; presentations; presentation slides; coding; coder; source code; compiler; development tools; code decompiler; JustDecompile; debugging code; debugger; Visual Studio; IDE; development environment; bug fixing; class library; API; C#; NET; NET Framework; types; variables; operators; expressions; statements; value types; reference types; type conversion; console; console input; console output; console application; conditional statements; if; if-else; switch-case; loops; whole; do-while; for loops; foreach; nested loops; arrays; matrices; multidimensional arrays; numeral systems; binary numbers; decimal numbers; hexadecimal numbers; representations of numbers; methods; method invocation; parameters; recursion; iteration; recursive algorithms; classes; objects; fields; constructors; properties; static fields; static methods; static constructor; static members; namespaces; exceptions; exception handling; stack trace; catch exception; throw exception; try-catch; try-finally; using statement; strings; text processing; StringBuilder; escaping; System.String; regular expressions; string formatting; OOP; object-oriented programming; access modifiers; public; private; protected; internal; this keyword; const fields; readonly fields; default constructor; implicit constructor; overloading; method overloading; constructor overloading; automatic properties; read-only properties; constants; enumerations; inner classes; nested classes; generics; generic types; generic methods; text files; streams; files; StreamReader; StreamWriter; data structures; ADT; abstract data structure; linear data structures; list; linked list; static list; doubly-linked list; array list; stack; queue; deque; trees; graphs; binary tree; binary search tree; balanced tree; balanced search tree; B-tree; red-black tree; tree traversal; ordered balanced search tree; graph representation; list of edges; list of successors; adjacency matrix; depth-first search; DFS; breadth-first search; BFS; dictionary; hash table; associative array; hash function; collision resolution; set; multi set; bag; multi bag; multi dictionary; algorithm complexity; asymptotic notation; time complexity; memory complexity; execution time; performance; collection classes; NET collections; Wintellect Power Collections; OOP; principles; abstraction; encapsulation; polymorphism; abstract class; interface; operation contract; virtual method; method overriding; cohesion; strong cohesion; coupling; loose coupling; spaghetti code; object-oriented modeling; UML; use-case diagram; sequence diagram; statechart diagram; activity diagram; design patterns; singleton; factory method; code quality; high-quality code; code conventions; naming identifiers; variable names; method names; naming classes; code formatting; high-quality classes; high-quality methods; variable scope; variable span; variable lifetime; control-flow statements; defensive programming; assertions; code documentation; documentation; selfdocumenting code; code refactoring; lambda expressions; LINQ; extension methods; anonymous types; LINQ queries; data filtering; data searching; data sorting; data grouping; problem solving; problem solving methodology; problems and solutions; generating ideas; task decomposition; algorithm efficiency; writing code; code testing; border cases testing; borderline cases; performance testing; regression testing; exercises; problems; solutions; programming guidelines; programming problems; programming exercises; good programmer; efficient programmer; pragmatic programmer; Nakov; Svetlin Nakov; Software Academy; Bulgaria; Bulgarian book; BG book; Bulgarian C# book; Kolev; Vesselin Kolev; Dilyan Dimitrov; Hristo Germanov; Iliyan Murdanliev; Mihail Stoynov; Mihail Valkov; Mira Bivas; Nikolay Kostov; Nikolay Nedyalkov; Nikolay Vassilev; Pavel Donchev; Pavlina Hadjieva; Radoslav Ivanov; Radoslav Kirilov; Radoslav Todorov; Stanislav Zlatinov; Stefan Staev; Teodor Bozhikov; Teodor Stoev; Tsvyatko Konov; Vesselin Georgiev; Yordan Pavlov; Yosif Yosifov, ISBN 9789544007737, ISBN 9544007733, ISBN 978-954-400-773-7, ISBN 954-400-773-3 Book Front Cover Contents Contents Detailed Table of Contents Preface 13 Chapter Introduction to Programming 69 Chapter Primitive Types and Variables 111 Chapter Operators and Expressions 139 Chapter Console Input and Output 165 Chapter Conditional Statements 195 Chapter Loops 211 Chapter Arrays 235 Chapter Numeral Systems 265 Chapter Methods 293 Chapter 10 Recursion 351 Chapter 11 Creating and Using Objects 385 Chapter 12 Exception Handling 415 Chapter 13 Strings and Text Processing 457 Chapter 14 Defining Classes 499 Chapter 15 Text Files 615 Chapter 16 Linear Data Structures 641 Chapter 17 Trees and Graphs 681 Chapter 18 Dictionaries, Hash-Tables and Sets 727 Chapter 19 Data Structures and Algorithm Complexity 769 Chapter 20 Object-Oriented Programming Principles 807 Chapter 21 High-Quality Programming Code 853 Chapter 22 Lambda Expressions and LINQ 915 Chapter 23 Methodology of Problem Solving 935 Chapter 24 Sample Programming Exam – Topic #1 985 Chapter 25 Sample Programming Exam – Topic #2 1041 Chapter 26 Sample Programming Exam – Topic #3 1071 Conclusion 1119 FUNDAMENTALS OF COMPUTER PROGRAMMING WITH C# (The Bulgarian C# Programming Book) Svetlin Nakov & Co Dilyan Dimitrov Radoslav Kirilov Hristo Germanov Radoslav Todorov Iliyan Murdanliev Stanislav Zlatinov Mihail Stoynov Stefan Staev Mihail Valkov Svetlin Nakov Mira Bivas Teodor Bozhikov Nikolay Kostov Teodor Stoev Nikolay Nedyalkov Tsvyatko Konov Nikolay Vasilev Vesselin Georgiev Pavel Donchev Veselin Kolev Pavlina Hadjieva Yordan Pavlov Radoslav Ivanov Yosif Yosifov Sofia, 2013 FUNDAMENTALS OF COMPUTER PROGRAMMING WITH C# (The Bulgarian C# Programming Book) © Svetlin Nakov & Co., 2013 The book is distributed freely under the following license conditions: Book readers (users) may: - distribute free of charge unaltered copies of the book in electronic or paper format; - use portions of the book and the source code examples or their modifications, for all intents and purposes, including educational and commercial projects, provided they clearly specify the original source, the original author(s) of the corresponding text or source code, this license and the website www.introprogramming.info; - distribute free of charge portions of the book or modified copies of it (including translating the book into other languages or adapting it to other programming languages and platforms), but only by explicitly mentioning the original source and the authors of the corresponding text, source code or other material, this license and the official website of the project: www.introprogramming.info Book readers (users) may NOT: - distribute for profit the book or portions of it, with the exception of the source code; - remove this license from the book when modifying it for own needs All trademarks referenced in this book are the property of their respective owners Official Web Site: http://www.introprogramming.info ISBN 978-954-400-773-7 Detailed Table of Contents Contents Detailed Table of Contents Preface 13 About the Book 13 C# and NET Framework 17 How То Read This Book? 22 Why Are Data Structures and Algorithms Emphasized? 25 Do You Really Want to Become a Programmer? 26 A Look at the Book’s Contents 29 History: How Did This Book Come to Be? 38 Authors and Contributors 40 The Book Is Free of Charge! 53 Reviews 53 License 63 Resources Coming with the Book 65 Chapter Introduction to Programming 69 In This Chapter 69 What Does It Mean "To Program"? 69 Stages in Software Development 71 Our First C# Program 75 The C# Language and the NET Platform 79 Visual Studio IDE 93 Alternatives to Visual Studio 104 Decompiling Code 104 C# in Linux, iOS and Android 107 Other NET Languages 107 Exercises 108 Solutions and Guidelines 108 Chapter Primitive Types and Variables 111 In This Chapter 111 What Is a Variable? 111 Data Types 111 Variables 123 Value and Reference Types 128 Literals 131 Fundamentals of Computer Programming with C# Exercises 135 Solutions and Guidelines 136 Chapter Operators and Expressions 139 In This Chapter 139 Operators 139 Type Conversion and Casting 152 Expressions 158 Exercises 160 Solutions and Guidelines 161 Chapter Console Input and Output 165 In This Chapter 165 What Is the Console? 165 Standard Input-Output 169 Printing to the Console 169 Console Input 183 Console Input and Output – Examples 190 Exercises 192 Solutions and Guidelines 193 Chapter Conditional Statements 195 In This Chapter 195 Comparison Operators and Boolean Expressions 195 Conditional Statements "if" and "if-else" 200 Conditional Statement "switch-case" 206 Exercises 208 Solutions and Guidelines 209 Chapter Loops 211 In This Chapter 211 What Is a "Loop"? 211 While Loops 211 Do-While Loops 216 For Loops 221 Foreach Loops 225 Nested Loops 226 Exercises 231 Solutions and Guidelines 233 Chapter Arrays 235 In This Chapter 235 What Is an "Array"? 235 Declaration and Allocation of Memory for Arrays 235 Access to the Elements of an Array 238 Reading an Array from the Console 241 Detailed Table of Contents Printing an Array to the Console 243 Iteration through Elements of an Array 244 Multidimensional Arrays 246 Arrays of Arrays 253 Exercises 257 Solutions and Guidelines 259 Chapter Numeral Systems 265 In This Chapter 265 History in a Nutshell 265 Numeral Systems 266 Representation of Numbers 276 Exercises 289 Solutions and Guidelines 290 Chapter Methods 293 In This Chapter 293 Subroutines in Programming 293 What Is a "Method"? 293 Why to Use Methods? 294 How to Declare, Implement and Invoke a Method? 295 Declaring Our Own Method 295 Implementation (Creation) of Own Method 300 Invoking a Method 301 Parameters in Methods 303 Returning a Result from a Method 328 Best Practices when Using Methods 345 Exercises 347 Solutions and Guidelines 348 Chapter 10 Recursion 351 In This Chapter 351 What Is Recursion? 351 Example of Recursion 351 Direct and Indirect Recursion 352 Bottom of Recursion 352 Creating Recursive Methods 352 Recursive Calculation of Factorial 353 Recursion or Iteration? 355 Simulation of N Nested Loops 356 Which is Better: Recursion or Iteration? 362 Using Recursion – Conclusions 378 Exercises 378 Solutions and Guidelines 380 Chapter 11 Creating and Using Objects 385 Fundamentals of Computer Programming with C# In This Chapter 385 Classes and Objects 385 Classes in C# 387 Creating and Using Objects 390 Namespaces 405 Exercises 410 Solutions and Guidelines 412 Chapter 12 Exception Handling 415 In This Chapter 415 What Is an Exception? 415 Exceptions Hierarchy 424 Throwing and Catching Exceptions 426 The try-finally Construct 432 IDisposable and the "using" Statement 437 Advantages of Using Exceptions 439 Best Practices when Using Exceptions 445 Exercises 453 Solutions and Guidelines 454 Chapter 13 Strings and Text Processing 457 In This Chapter 457 Strings 457 Strings Operations 462 Constructing Strings: the StringBuilder Class 480 String Formatting 488 Exercises 491 Solutions and Guidelines 496 Chapter 14 Defining Classes 499 In This Chapter 499 Custom Classes 499 Usage of Class and Objects 502 Organizing Classes in Files and Namespaces 505 Modifiers and Access Levels (Visibility) 508 Declaring Classes 509 The Reserved Word "this" 511 Fields 512 Methods 518 Accessing Non-Static Data of the Class 519 Hiding Fields with Local Variables 522 Visibility of Fields and Methods 524 Constructors 531 Properties 549 Static Classes and Static Members 559 Detailed Table of Contents Structures 580 Enumerations 584 Inner Classes (Nested Classes) 590 Generics 594 Exercises 610 Solutions and Guidelines 613 Chapter 15 Text Files 615 In This Chapter 615 Streams 615 Reading from a Text File 620 Writing to a Text File 628 Input / Output Exception Handling 630 Text Files – More Examples 631 Exercises 636 Solutions and Guidelines 638 Chapter 16 Linear Data Structures 641 In This Chapter 641 Abstract Data Structures 641 List Data Structures 642 Exercises 676 Solutions and Guidelines 678 Chapter 17 Trees and Graphs 681 In This Chapter 681 Tree Data Structures 681 Trees 681 Graphs 714 Exercises 722 Solutions and Guidelines 723 Chapter 18 Dictionaries, Hash-Tables and Sets 727 In This Chapter 727 Dictionary Data Structure 727 Hash-Tables 735 The "Set" Data Structure 760 Exercises 765 Solutions and Guidelines 767 Chapter 19 Data Structures and Algorithm Complexity 769 In This Chapter 769 Why Are Data Structures So Important? 769 Algorithm Complexity 770 Comparison between Basic Data Structures 779 When to Use a Particular Data Structure? 779 10 Fundamentals of Computer Programming with C# Choosing a Data Structure – Examples 786 External Libraries with NET Collections 801 Exercises 803 Solutions and Guidelines 804 Chapter 20 Object-Oriented Programming Principles 807 In This Chapter 807 Let’s Review: Classes and Objects 807 Object-Oriented Programming (OOP) 807 Fundamental Principles of OOP 808 Inheritance 809 Abstraction 824 Encapsulation 828 Polymorphism 830 Cohesion and Coupling 836 Object-Oriented Modeling (OOM) 842 UML Notation 844 Design Patterns 847 Exercises 851 Solutions and Guidelines 852 Chapter 21 High-Quality Programming Code 853 In This Chapter 853 Why Is Code Quality Important? 853 What Does Quality Programming Code Mean? 854 Why Should We Write Quality Code? 854 Identifier Naming 857 Code Formatting 866 High-Quality Classes 874 High-Quality Methods 878 Proper Use of Variables 883 Proper Use of Expressions 890 Use of Constants 891 Proper Use of Control Flow Statements 894 Defensive Programming 898 Code Documentation 900 Code Refactoring 904 Unit Testing 905 Additional Resources 912 Exercises 912 Solutions and Guidelines 913 Chapter 22 Lambda Expressions and LINQ 915 In This Chapter 915 Extension Methods 915 1108 Fundamentals of Computer Programming with C# string.Join(", ", this.Groups.Select(s => s.Name))); return teacherAsString.ToString(); } } Like in the class Group, it is important to create and empty list of groups instead of leaving the Groups property uninitialized Testing the Class Teacher Before going further, let’s test the class Teacher We can create a teacher with a few groups and print it at the console: static void Main() { Teacher teacherNatasha = new Teacher("Natasha", "Walters"); Group groupEnglish = new Group("English language"); Group groupFrench= new Group("French language"); teacherNatasha.Groups.Add(groupEnglish); teacherNatasha.Groups.Add(groupFrench); Console.WriteLine(teacherNatasha); } The result is correct: Teacher name: Natasha Walters Groups of this teacher: English language, French language This was expected We just repeated the same logic like in the Group class which was already tested and all bugs in it was fixed We found once again how important is to write the code step by step with testing and bugfixing after each step, right? The bug with incorrectly printing the list of students would have been repeated when printing the list of groups, right? Step 4: Class School We finish our object model with the definition of the class School, which uses all of the classes we already defined It should have a name and should hold a list of students, a list of teachers and a list of groups: public class School { public string Name { get; set; } public List Teachers { get; set; } public List Groups { get; set; } public List Students { get; set; } Chapter 26 Sample Programming Exam – Topic #3 1109 public School(string name) { this.Name = name; this.Teachers = new List(); this.Groups = new List(); this.Students = new List(); } } Before testing the class, let’s think what the class School is expected to It should hold the students, teachers and groups and should be printable at the console, right? If we print the school, what should be printed? Maybe we should print its name, all its students (with their inner details), all its teachers (with their inner details) and all its groups (with their inner details) Let’s try to define the ToString() method for the class School: public override string ToString() { StringBuilder schoolAsString = new StringBuilder(); schoolAsString.AppendLine("School name: " + this.Name); schoolAsString.AppendLine("Teachers: " + string.Join(", ", this.Teachers.Select(s => s.Name))); schoolAsString.AppendLine("Students: " + string.Join(", ", this.Students.Select(s => s.Name))); schoolAsString.Append("Groups: " + string.Join(", ", this.Groups.Select(s => s.Name))); foreach (var teacher in this.Teachers) { schoolAsString.Append("\n -\n"); schoolAsString.Append(teacher); } foreach (var group in this.Groups) { schoolAsString.Append("\n -\n"); schoolAsString.Append(group); } foreach (var student in this.Students) { schoolAsString.Append("\n -\n"); schoolAsString.Append(student); } return schoolAsString.ToString(); } 1110 Fundamentals of Computer Programming with C# We shall not test the class School, because this will be the main purpose of our last class: SchoolTest Step 5: Class SchoolTest The final thing is the implementation of the class SchoolTest the purpose of which is to demonstrate all the classes we have defined (Student, Group, Teacher and School) and their methods and properties This is our last subproblem For the demonstration we create a sample school with a few students, a few teachers and a few groups and we print it: SchoolTest.cs class TestSchool { static void Main() { // Create a few students Student studentPeter = new Student("Peter", "Lee"); Student studentGeorge = new Student("George", "Redwood"); Student studentMaria = new Student("Maria", "Steward"); Student studentMike = new Student("Michael", "Robinson"); // Create a group and add a few students to it Group groupEnglish = new Group("English language course"); groupEnglish.Students.Add(studentPeter); groupEnglish.Students.Add(studentMike); groupEnglish.Students.Add(studentMaria); groupEnglish.Students.Add(studentGeorge); // Create a group and add a few students to it Group groupJava = new Group("Java Programming course"); groupJava.Students.Add(studentMaria); groupJava.Students.Add(studentPeter); // Create a teacher and assign it to few groups Teacher teacherNatasha = new Teacher("Natasha", "Walters"); teacherNatasha.Groups.Add(groupEnglish); teacherNatasha.Groups.Add(groupJava); groupEnglish.Teacher = teacherNatasha; groupJava.Teacher = teacherNatasha; // Create another teacher and a group he teaches Teacher teacherSteve = new Teacher("Steve", "Porter"); Group groupHTML = new Group("HTML course"); groupHTML.Students.Add(studentMike); Chapter 26 Sample Programming Exam – Topic #3 1111 groupHTML.Students.Add(studentMaria); groupHTML.Teacher = teacherSteve; teacherSteve.Groups.Add(groupHTML); // Create a school with few students, groups and teachers School school = new School("Saint George High School"); school.Students.Add(studentPeter); school.Students.Add(studentGeorge); school.Students.Add(studentMaria); school.Students.Add(studentMike); school.Groups.Add(groupEnglish); school.Groups.Add(groupJava); school.Groups.Add(groupHTML); school.Teachers.Add(teacherNatasha); school.Teachers.Add(teacherSteve); // Modify some of the groups, student and teachers groupEnglish.Name = "Advanced English"; groupEnglish.Students.RemoveAt(0); studentPeter.LastName = "White"; teacherNatasha.LastName = "Hudson"; // Print the school Console.WriteLine(school); } } We run the program and we get the expected result: School name: Saint George High School Teachers: Natasha Hudson, Steve Porter Students: Peter White, George Redwood, Maria Steward, Michael Robinson Groups: Advanced English, Java Programming course, HTML course Teacher name: Natasha Hudson Groups of this teacher: Advanced English, Java Programming course Teacher name: Steve Porter Groups of this teacher: HTML course Group name: Advanced English Students in the group: Michael Robinson, Maria Steward, George 1112 Fundamentals of Computer Programming with C# Redwood Group teacher: Natasha Hudson Group name: Java Programming course Students in the group: Maria Steward, Peter White Group teacher: Natasha Hudson Group name: HTML course Students in the group: Michael Robinson, Maria Steward Group teacher: Steve Porter Student: Peter White Student: George Redwood Student: Maria Steward Student: Michael Robinson Of course in real life programs not start from the first time, but in this task the mistakes you could make are trivial so there’s no point in discussing them All classes are implemented and tested We are almost finished with this problem Testing the Solution As usually, it remains to test if the entire solution is working correctly We’ve already done this We tested all the classes in their nominal case We can some tests with the border cases, for instance a group without students, empty school, etc It seems like these cases work correctly We might test a student without a name, but it is unclear whether the class should keep itself of incorrect names and what is a correct name We can leave these classes without checks for the names It will be a responsibility of their caller to put correct names though their constructors and properties The problem description says nothing about this It is interesting how we delete a student In our current implementation, if we delete a student, we will need to remove it from the school and to remove it from all groups he belongs to The removal itself will require the student to have the Equals() method defined correctly or we should compare students by hand (property by property) It is unclear from the problem description how exactly the “delete student” operation should work We assume we don’t have time and we submit the solution in its current state without efficient delete operation Sometimes it takes too much time to fix something and it is better to leave it in not perfect form Below is the full source code of the solution of the school modeling problem: Chapter 26 Sample Programming Exam – Topic #3 School.cs using using using using System; System.Collections.Generic; System.Linq; System.Text; public class Student { public string FirstName { get; set; } public string LastName { get; set; } public Student(string firstName, string lastName) { this.FirstName = firstName; this.LastName = lastName; } public string Name { get { return this.FirstName + " " + this.LastName; } } public override string ToString() { return "Student: " + this.Name; } } public class Group { public string Name { get; set; } public List Students { get; set; } public Teacher Teacher { get; set; } public Group(string name) { this.Name = name; this.Students = new List(); } 1113 1114 Fundamentals of Computer Programming with C# public override string ToString() { StringBuilder groupAsString = new StringBuilder(); groupAsString.AppendLine("Group name: " + this.Name); groupAsString.Append("Students in the group: " + string.Join(", ", this.Students.Select(s => s.Name))); if (this.Teacher != null) { groupAsString.Append("\nGroup teacher: " + this.Teacher.Name); } return groupAsString.ToString(); } } public class Teacher { public string FirstName { get; set; } public string LastName { get; set; } public List Groups { get; set; } public Teacher(string firstName, string lastName) { this.FirstName = firstName; this.LastName = lastName; this.Groups = new List(); } public string Name { get { return this.FirstName + " " + this.LastName; } } public override string ToString() { StringBuilder teacherAsString = new StringBuilder(); teacherAsString.AppendLine("Teacher name: " + this.Name); teacherAsString.Append("Groups of this teacher: " + string.Join(", ", this.Groups.Select(s => s.Name))); return teacherAsString.ToString(); Chapter 26 Sample Programming Exam – Topic #3 1115 } } public class School { public string Name { get; set; } public List Teachers { get; set; } public List Groups { get; set; } public List Students { get; set; } public School(string name) { this.Name = name; this.Teachers = new List(); this.Groups = new List(); this.Students = new List(); } public override string ToString() { StringBuilder schoolAsString = new StringBuilder(); schoolAsString.AppendLine("School name: " + this.Name); schoolAsString.AppendLine("Teachers: " + string.Join(", ", this.Teachers.Select(s => s.Name))); schoolAsString.AppendLine("Students: " + string.Join(", ", this.Students.Select(s => s.Name))); schoolAsString.Append("Groups: " + string.Join(", ", this.Groups.Select(s => s.Name))); foreach (var teacher in this.Teachers) { schoolAsString.Append("\n -\n"); schoolAsString.Append(teacher); } foreach (var group in this.Groups) { schoolAsString.Append("\n -\n"); schoolAsString.Append(group); } foreach (var student in this.Students) { schoolAsString.Append("\n -\n"); schoolAsString.Append(student); } return schoolAsString.ToString(); 1116 Fundamentals of Computer Programming with C# } } class TestSchool { static void Main() { // Create a few students Student studentPeter = new Student("Peter", "Lee"); Student studentGeorge = new Student("George", "Redwood"); Student studentMaria = new Student("Maria", "Steward"); Student studentMike = new Student("Michael", "Robinson"); // Create a group and add a few students to it Group groupEnglish = new Group("English language course"); groupEnglish.Students.Add(studentPeter); groupEnglish.Students.Add(studentMike); groupEnglish.Students.Add(studentMaria); groupEnglish.Students.Add(studentGeorge); // Create a group and add a few students to it Group groupJava = new Group("Java Programming course"); groupJava.Students.Add(studentMaria); groupJava.Students.Add(studentPeter); // Create a teacher and assign it to few groups Teacher teacherNatasha = new Teacher("Natasha", "Walters"); teacherNatasha.Groups.Add(groupEnglish); teacherNatasha.Groups.Add(groupJava); groupEnglish.Teacher = teacherNatasha; groupJava.Teacher = teacherNatasha; // Create another teacher and a group he teaches Teacher teacherSteve = new Teacher("Steve", "Porter"); Group groupHTML = new Group("HTML course"); groupHTML.Students.Add(studentMike); groupHTML.Students.Add(studentMaria); groupHTML.Teacher = teacherSteve; teacherSteve.Groups.Add(groupHTML); // Create a school with few students, groups and teachers School school = new School("Saint George High School"); school.Students.Add(studentPeter); school.Students.Add(studentGeorge); Chapter 26 Sample Programming Exam – Topic #3 1117 school.Students.Add(studentMaria); school.Students.Add(studentMike); school.Groups.Add(groupEnglish); school.Groups.Add(groupJava); school.Groups.Add(groupHTML); school.Teachers.Add(teacherNatasha); school.Teachers.Add(teacherSteve); // Modify some of the groups, student and teachers groupEnglish.Name = "Advanced English"; groupEnglish.Students.RemoveAt(0); studentPeter.LastName = "White"; teacherNatasha.LastName = "Hudson"; // Print the school Console.WriteLine(school); } } We will not run performance tests because the task is not of a computational nature which requires a fast algorithm Operations that could be slow are deleting of elements from a collection Creating objects, assigning their properties and adding elements to their collections of child elements are all fast operations Only the deletion could be slow We could improve its performance by using HashSet instead of List in all aggregations We leave this to the reader Let’s make just one more note Why we did not notice the performance problem with deleting elements earlier? Let’s recall how we proceeded with solving this problem After thinking about the data structures we had to thing about the performance right? Did we this step? We omitted this step and we found the problem too late The conclusion is: follow the guidelines for problem solving They are very wise Exercises Write a program, which prints a square spiral matrix beginning from the number in the upper right corner and moving clockwise Examples for N=3 and N=4: 10 11 12 16 13 15 14 1118 Fundamentals of Computer Programming with C# Write a program, which counts the phrases in a text file Any sequence of characters could be given as phrase for counting, even sequences containing separators For instance in the text "I am a student in Sofia" the phrases "s", "stu", "a" and "I am" are found respectively 2, 1, and times Model with OOP the file system of a computer running Windows We have devices, directories and files The devices are for instance floppy disk, HDD, CD-ROM, etc They have a name and a tree of directories and files Each directory has a name, date of last change and list of files and directories, which it holds Each file has a name, date of creation, date of last change and content Each file is placed in one of the directories Each file can be text or binary Text files contain text (string), and the binary ones – sequence of bytes (byte[]) Create a class, which tests the other classes and demonstrates how we can build a model for devices, directories and files in the computer Using the classes from the previous task write a program which takes the real file system from your computer and loads it in your classes (just the names of the devices, directories and files, without the content of the files because you will run out of memory) Solutions and Guidelines The task is analogical to the first task of the sample exam You can modify the sample solution given above You may read the text char by char and after each char to append it to the current buffer buf and check each of the searched word for a match with EndsWith() in the buffer’s end Of course you cannot use efficiently hash-table and you will have a loop for each letter from the text, which is not the fastest solution This is a modification of the “char by char algorithm for word counting” Implementing a faster solution needs to adapt the Aho-Corasick algorithm Try to play with it and modify the code from the section “Counting Substrings with the Aho-Corasick Algorithm” The problem is analogical with the “School” problem from the sample exam and it can be solved by using the same approach Define classes Device, Directory, File, ComputerStorage and ComputerStorageTest Think of what properties each of these classes has and what are the relationships between the classes Create a base abstract class File and inherit it from TextFile and BinaryFile Test your code with sample hierarchy of devices, files and folders Note: a file can be listed in more than one directory at the same time (unlike in the file system) Use the class System.IO.Directory and its static methods GetFiles(), GetDirectories() and GetLogicalDrives() Traverse the files system using the BFS or DFS graph traversal algorithm Load partially the content of long files (e.g the first 128 bytes / chars) to save memory Conclusion If you are reading this conclusion and if you have read carefully the entire book, then please accept our well-deserved congratulations! We are certain that you have earned valuable knowledge in the principles of programming that will stick for life Even if the years pass, even if technology evolves and computers are far from their current state, the fundamental knowledge of data structures in programming and the algorithmic way of thinking as well as the experience gained in solving programming problems will always aid you, if you work in the field of information technology Did You Solve All Problems? If you have solved all problems from all chapters, in addition to reading carefully the entire book, then you can proudly declare yourself a programmer Whatever technology you pick up from now on will be child’s play Now that you have grasped the basics and fundamental principles of programming, you’ll easily learn to use databases and SQL, develop Web applications and server-side software (e.g with ASP.NET and WCF), write HTML5 applications, develop for mobile devices and whatever else you’d like You have a great advantage over the majority of programmers who not know what a hash-table is, how searching in a tree works and what algorithm complexity is If you have really made the tremendous effort to solve all problems from the book, then you have most certainly reached a level of fundamental understanding of the concepts of programming and a programmer’s way of thinking, which will aid you for many years Have You Encountered Difficulties with the Exercises? If you haven’t solved all exercise problems or at least the vast majority of them, turn back and solve them! Yes, it does take a lot of time, but that’s the way to learn programming – with a lot of work and effort You won’t learn programming without practicing it diligently! If you have encountered difficulties, use the discussion forum of the courses on fundamentals of programming at the Software Academy, which follow this book: http://forums.academy.telerik.com Several hundred people have taken these courses and the majority of them have solved all problems and shared their solutions So, examine them, try solving the problems and then try again without using any guides 1120 Fundamentals of Computer Programming with C# Many lectures and video tutorials have been uploaded on the book’s Web site (http://www.introprogramming.info) We have free PowerPoint slides and videos in English and Bulgarian for each chapter of the book They will be of great use to you, especially if this is the first time you are getting involved in programming If you decide to teach C#, programming or data structures and algorithms, the slides and exercises will help you focus on the training and save time preparing the content It’s worth checking them out Also, check out the free courses available from Telerik Software Academy (http://academy.telerik.com) All of their lectures' study materials and video recordings have been made available for free download on each course’s respective Web site These courses are an excellent follow-up to your progress as software engineers and professionals in software development All materials (lecture slides, exercises, demos) and some video recordings, both at this book’s and at Telerik Academy’s Web site, are available in English How Do You Proceed After Reading the Book? Maybe you are wondering how you should continue your development as a software engineer You’ve laid solid foundations with this book, so it won’t be difficult We can give you the following instructions: Choose a language and a programming platform, e g C# + NET Framework, Java + Java EE, Ruby + Rails or PHP + CakePHP There’s nothing wrong with giving up C# Focus on the technologies your platform supports; you’ll learn the corresponding language quickly For example, if you choose Objective-C and iPhone / iPad / iOS / Xcode programming, the algorithmic way of thinking you have acquired with this book will help you make progress Read a book on databases and learn how to model your application’s data using tables and relations between them Learn how to build queries for selecting and updating data in SQL Learn how to work with a database server, like Oracle, SQL Server or MySQL The next natural course of action is to acquire some ORM technology, like ADO.NET Entity Framework, Hibernate or JPA You might also try the NoSQL database systems available in the public clouds Acquire a technology for building dynamic Web sites Start with a book on HTML, CSS, JavaScript and jQuery, or with our free course on HTML5, CSS3 and JavaScript (http://html5course.telerik.com) Then explore the web development tools your platform supports, such as ASP.NET Web Forms / ASP.NET MVC using the NET Platform and C#, Servlets / JSP / JSF using the Java platform, CakePHP / Symfony / Zend Framework with PHP, Ruby on Rails using Ruby or Django using Python Learn how to make simple Web sites with dynamic content Try creating a Web application for mobile devices using some mobile UI toolkit Learn to write mobile applications Start for example with HTML5 and Cordova, try to deploy your apps in the large marketplaces maintained by Google, Apple, Microsoft and Amazon Try to learn native mobile Conclusion 1121 development (e.g Java and Android development or Objective C and iOS development) Create a mobile app (e.g some game) and deploy it in some major marketplace Thus you will pass through the entire design / develop /publish cycle and this will give you real-world mobile development experience Take up working on a more serious project, like a Web market or a program for managing warehouse or accounting software This will give you the opportunity to encounter the practical problems of practical software development You’ll gain the more valuable practical experience and you’ll see for yourself that coding advanced software is much more difficult than coding simple programs Get a job at a software company! This is very important If you have really solved all problems from this book, you’ll easily get a job offer By working on practical software projects you’ll learn a great deal of new software technologies, unlike your colleagues, and you’ll come to realize that, even though you know a lot about programming, you are only at the very beginning of your career as a software engineer You’ll only get to tackle the challenges of team work in practice, and acquire the tools for dealing with them by working on actual software projects at an actual work environment You’ll have to work at least for a few years until you establish yourself as a software development professional Then, perhaps, you’ll remember about this book and you’ll realize that you haven’t gone wrong by starting with data structures and algorithms rather than directly with Web technologies, databases and mobile development Free Courses at Telerik Software Academy You can save yourself a lot of trouble and nerves, if you decide to go through all of the above steps of your development as a software engineer at Telerik Software Academy You’ll learn under the guidance of Svetlin Nakov and instructors with practical experience in the software industry The Academy is the easiest and absolutely free-of-charge way to lay the foundations of your development career, but it is not the only way Everything depends on you! Good Luck to Everyone! On behalf of the entire panel of authors, we wish you endless success in your career and personal life! Svetlin Nakov, Manager of the "Technical Training" Department, Telerik Corporation, Telerik Software Academy – http://academy.telerik.com August 24th, 2013 Fundamentals of Computer Programming with C# (The Bulgarian C# Programming Book) by Svetlin Nakov and Co http://www.introprogramming.info Book Back Cover [...]... thinking and knowledge of all basic data structures and algorithms The information below comes from Svetlin Nakov, the leading author of this book, who passed software engineering interviews at Microsoft and Google in 2007-2008 and shares his own experience 26 Fundamentals of Computer Programming with C# Job Interviews at Google 100% of the questions at job interviews for software engineers at Google,... become a developer There is no other way! Do Not Skip the Exercises! At the end of each chapter there is a considerable list of exercises Do not skip them! Without exercises, you will not learn a thing After you read a 24 Fundamentals of Computer Programming with C# chapter, you should sit in front of the computer and play with the examples you have seen in the book Then you should set about solving... skills that even experienced professional programmers lack Software companies are riddled with a shocking amount of self-taught amateurs who, despite having programmed on a salary for years, have no grasp of the fundamentals of programming and have no idea what a hash table is, how polymorphism works and how to work with bitwise operations Don’t be like them! Learn the basics of programming first and then... technology, programming languages, operation systems, compilers, computer graphics, games, hardware, artificial intelligence and everything else related to computers and technologies The more they learn, the more knowledge and skills they crave after Their life is tied to technologies and they change 28 Fundamentals of Computer Programming with C# with them, enjoying the development of computer science,... Framework, which will help us in our study of the language’s capabilities Author of the chapter is Pavel Donchev; editors are Teodor Bozhikov and Svetlin Nakov The content of the chapter is somewhat based on the work of 30 Fundamentals of Computer Programming with C# Luchesar Cekov from the book "Introduction to Programming with Java" Translation to English: by Atanas Valchev (edited by Vladimir Tsenev... formatting of text content on the console, with various ways for printing numbers and dates Author of the chapter is Veselin Georgiev and editor is Radoslav Todorov The content of the entire chapter is based on the work of Mario Peshev from the book "Introduction to Programming with Java" Translation to English: by Vesselin Georgiev (edited by Todor Mitev and Vladimir Amiorkov) 34 Fundamentals of Computer Programming. .. and show you how useful they are Author of the chapter is Hristo Germanov and editor is Radoslav Todorov The content of the chapter is based on the work of Mariyan Nenchev from the book "Introduction to Programming with Java" Translation to English: by Boyan Dimitrov (edited by Radoslav Todorov and Zhelyazko Dimitrov) 32 Fundamentals of Computer Programming with C# Chapter 8: Numeral Systems In the... we will familiarize ourselves with some of the basic representations of data in programming and with linear data structures, because very often, in order to solve a given problem, we need to work with a sequence of elements For example, to read this book we have to read consecutively every single page, e.g we have to traverse consecutively every single element of its set of pages We are going to see... preface also describes the history of the book, the content of its chapter one by one, the team of authors, editors and translators from Bulgarian to English In contains the full reviews written by famous software engineers from Microsoft, Google, SAP, VMware, Telerik and other leading software companies from all over the world Author of the preface is Svetlin Nakov (with little contribution from Veselin... to Programming In the chapter "Introduction to Programming" , we will take a look at the basic terminology in programming and write our first program We will familiarize ourselves with what programming is and what connection to computers and programming languages it has We will briefly review the main stages in software development, introduce the C# language, the NET platform and the different Microsoft ... significant 18 Fundamentals of Computer Programming with C# Nevertheless, let’s give a short account of C# (pronounced "see sharp") C# is a modern programming language for development of software applications... to technologies and they change 28 Fundamentals of Computer Programming with C# with them, enjoying the development of computer science, technologies and the software industry Everything we tell... Author of the chapter is Pavel Donchev; editors are Teodor Bozhikov and Svetlin Nakov The content of the chapter is somewhat based on the work of 30 Fundamentals of Computer Programming with C#

Ngày đăng: 05/12/2016, 12:47

Từ khóa liên quan

Mục lục

  • Contents

  • Detailed Table of Contents

  • Preface

    • About the Book

      • Please Excuse Us for the Bugs in the Translation!

      • Who Is This Book Aimed At?

      • Previous Knowledge Is Not Required!

      • What Is the Scope of This Book?

      • What Will This Book Not Teach You?

      • How Is the Information Presented?

      • C# and .NET Framework

        • The C# Programming Language

        • The Microsoft .NET Framework

        • Why C#?

          • C# or Java?

          • Why Not PHP?

          • Why Not C or C++?

          • Advantages of C#

          • Examples Are Given in C# 5 and Visual Studio 2012

          • How То Read This Book?

            • Do Not Skip the Exercises!

            • How Much Time Will We Need for This Book?

            • Exercises: Complex or Easy?

            • Why Are Data Structures and Algorithms Emphasized?

              • Job Interviews at Google

              • Job Interviews at Microsoft

Tài liệu cùng người dùng

Tài liệu liên quan