Common Type System

  1. Define a classStudent, which contains data about a student – first, middle and last name, SSN, permanent address, mobile phone e-mail, course, specialty, university, faculty. Use an enumeration for the specialties, universities and faculties. Override the standard methods, inherited by System.Object:Equals(),ToString(),GetHashCode()and operators==and!=.
  2. Add implementations of the ICloneableinterface. The Clone()method should deeply copy all object’s fields into a new object of type Student.
  3. Implement the IComparable<Student>interface to compare students by names (as first criteria, in lexicographic order) and by social security number (as second criteria, in increasing order).GitHub Link
  4. Create a class Person with two fields – name and age. Age can be left unspecified (may contain nullvalue. Override ToString() to display the information of a person and if age is not specified – to say so. Write a program to test this functionality.GitHub Link
  5. Define a class BitArray64 to hold 64 bit values inside an ulong value. Implement IEnumerable<int> and Equals(…), GetHashCode(), [], == and !=.GitHub Link
  6. * Define the data structure binary search tree with operations for “adding new element”, “searching element” and “deleting elements”. It is not necessary to keep the tree balanced. Implement the standard methods from System.Object – ToString(), Equals(…),GetHashCode()and the operators for comparison ==and!=.Add and implement the ICloneable interface for deep copy of the tree. Remark: Use two types – structure BinarySearchTree (for the tree) and classTreeNode (for the tree elements). Implement IEnumerable<T> to traverse the tree.GitHub Link

Object Oriented Programming Fundamental Principles Part II

  1. Define abstract class Shape with only one abstract method CalculateSurface() and fields width and height. Define two new classes Triangle and Rectangle that implement the virtual method and return the surface of the figure (height*width for rectangle and height*width/2 for triangle). Define class Circle and suitable constructor so that at initialization height must be kept equal to width and implement the CalculateSurface() method. Write a program that tests the behavior of the CalculateSurface() method for different shapes(Circle, Rectangle, Triangle) stored in an array.GitHub Link
  2. A bank holds different types of accounts for its customers: deposit accounts, loan accounts and mortgage accounts. Customers could be individuals or companies.
    All accounts have customer, balance and interest rate (monthly based). Deposit accounts are allowed to deposit and with draw money. Loan and mortgage accounts can only deposit money.All accounts can calculate their interest amount for a given period (in months). In the common case its is calculated as follows: number_of_months * interest_rate.Loan accounts have no interest for the first 3 months if are held by individuals and for the first 2 months if are held by a company.

    Deposit accounts have no interest if their balance is positive and less than 1000.

    Mortgage accounts have ½ interest for the first 12 months for companies and no interest for the first 6 months for individuals.

    Your task is to write a program to model the bank system by classes and interfaces. You should identify the classes, interfaces, base classes and abstract actions and implement the calculation of the interest functionality through overridden methods.

    GitHub Link

  3. Define a class InvalidRangeException<T> that holds information about an error condition related to invalid range. It should hold error message and a range definition [start … end].
    Write a sample application that demonstrates the InvalidRangeException<int>and InvalidRangeException<DateTime>by entering numbers in the range [1..100] and dates in the range [1.1.1980 … 31.12.2013].GitHub Link

Object Oriented Programming Fundamental Principles Part I

 

  1. We are given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique class number. Classes have unique text identifier. Teachers have name. Disciplines have name, number of lectures and number of exercises. Both teachers and students are people. Students, classes, teachers and disciplines could have optional comments (free text block).
    Your task is to identify the classes (in terms of OOP) and their attributes and operations, encapsulate their fields, define the class hierarchy and create a class diagram with Visual Studio. 

    GitHub Link 

  2. Define abstract class Human with first name and last name. Define new class Student which is derived from Human and has new field – grade. Define class Worker derived from Human with new property WeekSalary and WorkHoursPerDay and method MoneyPerHour() that returns money earned by hour by the worker. Define the proper constructors and properties for this hierarchy. Initialize a list of 10 students and sort them by grade in ascending order (use LINQ or OrderBy() extension method). Initialize a list of 10 workers and sort them by money per hour in descending order. Merge the lists and sort them by first name and last name.GitHub Link
  3. Create a hierarchy Dog, Frog, Cat, Kitten, Tomcat and define useful constructors and methods. Dogs, frogsand cats are Animals. All animals can produce sound (specified by the ISound interface). Kittens and tomcats are cats. All animals are described by age, name and sex. Kittens can be only female and tomcats can be only male. Each animal produces a specific sound. Create arrays of different kinds of animals and calculate the average age of each kind of animal using a static method (you may use LINQ)GitHub Link

Extension Methods, Lambda Expressions and LINQ

  1. Implement an extension method Substring(int index, int length) for the class StringBuilder that returns new StringBuilder and has the same functionality as Substring in the class String.GitHub Link
  2. Implement a set of extension methods for IEnumerable<T> that implement the following group functions: sum, product, min, max, average.GitHub Link
  3. Write a method that from a given array of students finds all students whose first name is before its last name alphabetically. Use LINQ query operators.GitHub Link
  4. Write a LINQ query that finds the first name and last name of all students with age between 18 and 24.GitHub Link
  5. Using the extension methods OrderBy() and ThenBy() with lambda expressions sort the students by first name and last name in descending order. Rewrite the same with LINQ.GitHub Link
  6. Write a program that prints from given array of integers all numbers that are divisible by 7 and 3. Use the built-in extension methods and lambda expressions. Rewrite the same with LINQ.GitHub Link
  7. Using delegates write a class Timer that has can execute certain method at each t seconds.GitHub Link

Defining Classes – Part II

  1. Create a structure Point3D to hold a 3D-coordinate {X, Y, Z} in the Euclidian 3D space. Implement the ToString() to enable printing a 3D point.
  2. Add a private static read-only field to hold the start of the coordinate system – the point O{0, 0, 0}. Add a static property to return the point O.
  3. Write a static class with a static method to calculate the distance between two points in the 3D space.
  4. Create a class Path to hold a sequence of points in the 3D space. Create a static class PathStorage with static methods to save and load paths from a text file. Use a file format of your choice.GitHub Link
  5. Write a generic class GenericList<T> that keeps a list of elements of some parametric type T. Keep the elements of the list in an array with fixed capacity which is given as parameter in the class constructor. Implement methods for adding element, accessing element by index, removing element by index, inserting element at given position, clearing the list, finding element by its value and ToString(). Check all input parameters to avoid accessing elements at invalid positions.
  6. Implement auto-grow functionality: when the internal array is full, create a new array of double size and move all elements to it.
  7. Create generic methods Min<T>() and Max<T>() for finding the minimal and maximal element in the  GenericList<T>. You may need to add a generic constraints for the type T.

    GitHub Link

  8. Define a class Matrix<T> to hold a matrix of numbers (e.g. integers, floats, decimals).
  9. Implement an indexer this[row, col] to access the inner matrix cells.
  10. Implement the operators + and – (addition and subtraction of matrices of the same size) and * for matrix multiplication. Throw an exception when the operation cannot be performed. Implement the true operator (check for non-zero elements).

    GitHub Link

  11. Create a [Version] attribute that can be applied to structures, classes, interfaces, enumerations and methods and holds a version in the format major.minor (e.g. 2.11). Apply the version attribute to a sample class and display its version at runtime.

    GitHub Link

Defining Classes – Part I

  1. Define a class that holds information about a mobile phone device: model, manufacturer, price, owner, battery characteristics (model, hours idle and hours talk) and display characteristics (size and number of colors). Define 3 separate classes (class GSM holding instances of the classes Battery and Display).

  2. Define several constructors for the defined classes that take different sets of arguments (the full information for the class or part of it). Assume that model and manufacturer are mandatory (the others are optional). All unknown data fill with null.

  3. Add an enumeration BatteryType (Li-Ion, NiMH, NiCd, …) and use it as a new field for the batteries.

  4. Add a method in the GSM class for displaying all information about it. Try to override ToString().

  5. Use properties to encapsulate the data fields inside the GSM, Battery and Display classes. Ensure all fields hold correct data at any given time.

  6. Add a static field and a property IPhone4S in the GSM class to hold the information about iPhone 4S.

  7. Write a class GSMTest to test the GSM class:
    • ­Create an array of few instances of the GSM class.
    • ­Display the information about the GSMs in the array.
    • ­Display the information about the static property IPhone4S.
  8. Create a class Call to hold a call performed through a GSM. It should contain date, time, dialed phone number and duration (in seconds).

  9. Add a property CallHistory in the GSM class to hold a list of the performed calls. Try to use the system class List<Call>.

  10. Add methods in the GSM class for adding and deleting calls from the calls history. Add a method to clear the call history.

  11. Add a method that calculates the total price of the calls in the call history. Assume the price per minute is fixed and is provided as a parameter.

  12. Write a class GSMCallHistoryTest to test the call history functionality of the GSM class.
    • ­Create an instance of the GSM class.
    • ­Add few calls.
    • ­Display the information about the calls.
    • ­Assuming that the price per minute is 0.37 calculate and print the total price of the calls in the history.
    • ­Remove the longest call from the history
    • and calculate the total price again.Finally clear the call history and print it.

    GitHub Link

Strings and Text Processing

  1. Describe the strings in C#. What is typical for the string data type? Describe the most important methods of the String class.GitHub Link
  2. Write a program that reads a string, reverses it and prints the result at the console.
    Example: “sample” -> “elpmas”.GitHub Link
  3. Write a program to check if in a given expression the brackets are put correctly.
    Example of correct expression: ((a+b)/5-d).
    Example of incorrect expression: )(a+b)).GitHub Link
  4. Write a program that finds how many times a substring is contained in a given text (perform case insensitive search).
    Example:
    The target substring is “in”.
    The text is as follows:
    We are living in an yellow submarine.
    We don’t have anything else.
    Inside the submarine is very tight.
    So we are drinking all the day.
    We will move out of it in 5 days.The result is: 9.GitHub Link
  5. You are given a text. Write a program that changes the text in all regions surrounded by the tags <upcase> and </upcase> to uppercase. The tags cannot be nested.
    Example:
    We are living in a <upcase>yellow submarine</upcase>.
    We don’t have <upcase>anything</upcase> else.
    The expected result:
    We are living in a YELLOW SUBMARINE. We don’t have ANYTHING else.GitHub Link
  6. Write a program that reads from the console a string of maximum 20 characters. If the length of the string is less than 20, the rest of the characters should be filled with ‘*’. Print the result string into the console.GitHub Link
  7. Write a program that encodes and decodes a string using given encryption key (cipher). The key consists of a sequence of characters. The encoding/decoding is done by performing XOR (exclusive or) operation over the first letter of the string with the first of the key, the second – with the second, etc. When the last key character is reached, the next is the first.GitHub Link
  8. Write a program that extracts from a given text all sentences containing given word.
    Example: The word is “in”.
    We are living in a yellow submarine. We don’t have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.
    The text is:
    We are living in a yellow submarine.
    We will move out of it in 5 days.
    Consider that the sentences are separated by “.” and the words – by non-letter symbols.GitHub Link
  9. We are given a string containing a list of forbidden words and a text containing some of these words. Write a program that replaces the forbidden words with asterisks.
    Example:
    Microsoft announced its next generation PHP compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language in CLR.
    Words: “PHP, CLR, Microsoft”
    The expected result:
    ********* announced its next generation *** compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language in ***.GitHub Link
  10. Write a program that converts a string to a sequence of C# Unicode character literals. Use format strings.
    Sample input:
    Hi!
    Expected output:
    \u0048\u0069\u0021GitHub Link
  11. Write a program that reads a number and prints it as a decimal number, hexadecimal number, percentage and in scientific notation. Format the output aligned right in 15 symbols.GitHub Link
  12. Write a program that parses an URL address given in the format: [protocol]://[server]/[resource] and extracts from it the [protocol], [server] and [resource] elements.
    For example from the URL http://www.devbg.org/forum/index.php the following information should be extracted:
    [protocol] = “http”
    [server] = “www.devbg.org”
    [resource] = “/forum/index.php”GitHub Link
  13. Write a program that reverses the words in given sentence.
    Example: “C# is not C++, not PHP and not Delphi!” -> “Delphi not and PHP, not C++ not is C#!”.GitHub Link
  14. A dictionary is stored as a sequence of text lines containing words and their explanations. Write a program that enters a word and translates it by using the dictionary.
    Sample dictionary:
    .NET – platform for applications from Microsoft
    CLR – managed execution environment for .NET
    namespace – hierarchical organization of classesGitHub Link
  15. Write a program that replaces in a HTML document given as string all the tags <a href=”…”>…</a> with corresponding tags [URL=…]…/URL].
    Sample HTML fragment:
    <p>Please visit <a href=”http://academy.telerik. com”>our site</a> to choose a training course.
    Also visit <a href=”www.devbg.org”>our forum</a> to discuss the courses.</p><p>Please visit [URL=http://academy.telerik. com]our site[/URL] to choose a training course.
    Also visit [URL=www.devbg.org]our forum[/URL] to discuss the courses.</p>GitHub Link
  16. Write a program that reads two dates in the format: day.month.year and calculates the number of days between them.
    Example:
    Enter the first date: 27.02.2006
    Enter the second date: 3.03.2004
    Distance: 4 daysGitHub Link
  17. Write a program that reads a date and time given in the format: day.month.year hour:minute:second and prints the date and time after 6 hours and 30 minutes (in the same format) along with the day of week in Bulgarian.GitHub Link
  18. Write a program for extracting all email addresses from given text. All substrings that match the format <identifier>@<host>…<domain> should be recognized as emails.GitHub Link
  19. Write a program that extracts from a given text all dates that match the format DD.MM.YYYY. Display them in the standard date format for Canada.GitHub Link
  20. Write a program that extracts from a given text all palindromes, e.g. “ABBA”, “lamal”, “exe”.GitHub Link
  21. Write a program that reads a string from the console and prints all different letters in the string along with information how many times each letter is found.GitHub Link
  22. Write a program that reads a string from the console and lists all different words in the string along with information how many times each word is found.GitHub Link
  23. Write a program that reads a string from the console and replaces all series of consecutive identical letters with a single one.
    Example: “aaaaabbbbbcdddeeeedssaa” -> “abcdedsa”.GitHub Link
  24. Write a program that reads a list of words, separated by spaces and prints the list in an alphabetical order.GitHub Link
  25. Write a program that extracts from given HTML file its title (if available), and its body text without the HTML tags.
    Example:
    <html>
    <head><title>News</title></head>
    <body>
    <p><a href=”http://academy.telerik.com”>Telerik
    Academy</a>aims to provide free real-world practical
    training for young people who want to turn into
    skillful .NET software engineers.
    </p>
    </body>
    </html>GitHub Link

Text Files

  1. Write a program that reads a text file and prints on the console its odd lines.GitHub Link
  2. Write a program that concatenates two text files into another text file.GitHub Link
  3. Write a program that reads a text file and inserts line numbers in front of each of its lines. The result should be written to another text file.GitHub Link
  4. Write a program that compares two text files line by line and prints the number of lines that are the same and the number of lines that are different. Assume the files have equal number of lines.GitHub Link
  5. Write a program that reads a text file containing a square matrix of numbers and finds in the matrix an area of size 2 x 2 with a maximal sum of its elements. The first line in the input file contains the size of matrix N. Each of the next N lines contain N numbers separated by space. The output should be a single number in a separate text file. Example:
    4
    2 3 3 4
    0 2 3 4     -> 17
    3 7 1 2
    4 3 3 2GitHub Link
  6. Write a program that reads a text file containing a list of strings, sorts them and saves them to another text file. Example:
    Ivan            George
    Peter ——->    Ivan
    Maria            Maria
    George            PeterGitHub Link
  7. Write a program that replaces all occurrences of the substring “start” with the substring “finish” in a text file. Ensure it will work with large files (e.g. 100 MB).GitHub Link
  8. Modify the solution of the previous problem to replace only whole words (not substrings).GitHub Link
  9. Write a program that deletes from given text file all odd lines. The result should be in the same file.GitHub Link
  10. Write a program that extracts from given XML file all the text without the tags.
    Example:
    <?xml version=”1.0″>
    <student>
    <name>Pesho</name>
    <age>21</age>
    <interests count=”3″>
    <interest> Games</instrest>
    <interest>C#</instrest>
    <interest> Java</instrest>
    </interests>
    </student>GitHub Link
  11. Write a program that deletes from a text file all words that start with the prefix “test”. Words contain only the symbols 0…9, a…z, A…Z, _.GitHub Link
  12. Write a program that removes from a text file all words listed in given another text file. Handle all possible exceptions in your methods.GitHub Link
  13. Write a program that reads a list of words from a file words.txt and finds how many times each of the words is contained in another file test.txt. The result should be written in the file result.txt and the words should be sorted by the number of their occurrences in descending order. Handle all possible exceptions in your methods.GitHub Link

Exception Handling

  1. Write a program that reads an integer number and calculates and prints its square root. If the number is invalid or negative, print “Invalid number”. In all cases finally print “Good bye”. Use try-catch-finally.

    GitHub Link

     
  2. Write a method ReadNumber(int start, int end) that enters an integer number in given range [start…end]. If an invalid number or non-number text is entered, the method should throw an exception. Using this method write a program that enters 10 numbers:

    a1, a2, … a10, such that 1 < a1 < … < a10 < 100

    GitHub Link

  3. Write a program that enters file name along with its full file path (e.g. C:\WINDOWS\win.ini), reads its contents and prints it on the console. Find in MSDN how to use System.IO.File.ReadAllText(…). Be sure to catch all possible exceptions and print user-friendly error messages.

    GitHub Link

     
  4. Write a program that downloads a file from Internet (e.g. http://www.devbg.org/img/Logo-BASD.jpg) and stores it the current directory. Find in Google how to download files in C#. Be sure to catch all exceptions and to free any used resources in the finally block.

    GitHub Link

Using Classes and Objects

  1. Write a program that reads a year from the console and checks whether it is a leap. Use DateTime.

    GitHub Link

  2. Write a program that generates and prints to the console 10 random values in the range [100, 200].

    GitHub Link

  3. Write a program that prints to the console which day of the week is today. Use System.DateTime.

    GitHub Link

  4. Write methods that calculate the surface of a triangle by given:
    • ­Side and an altitude to it;
    • Three sides;
    • Two sides and an angle between them.

    Use System.Math.

    GitHub Link

  5. Write a method that calculates the number of workdays between today and given date, passed as parameter. Consider that workdays are all days from Monday to Friday except a fixed list of public holidays specified preliminary as array.

    GitHub Link

     
  6. You are given a sequence of positive integer values written into a string, separated by spaces. Write a function that reads these values from given string and calculates their sum. Example:

    string = “43 68 9 23 318” -> result = 461

    GitHub Link

  7. * Write a program that calculates the value of given arithmetical expression. The expression can contain the following elements only:
    • Real numbers, e.g. 5, 18.33, 3.14159, 12.6
    • Arithmetic operators: +, -, *, / (standard priorities)
    • Mathematical functions: ln(x), sqrt(x), pow(x,y)
    • Brackets (for changing the default priorities)

    Examples:

    (3+5.3) * 2.7 – ln(22) / pow(2.2, -1.7) -> ~ 10.6

    pow(2, 3.14) * (3 – (3 * sqrt(2) – 3.2) + 1.5*0.3) -> ~ 21.22

    Hint: Use the classical “shunting yard” algorithm and “reverse Polish notation”.

    GitHub Link