# Exercises

Possible exercises for the C# lecture.

## 1. Let's get started

Let's display some messages on the console and request the user to enter his name. Output a friendly welcome message with the user's name.

Run this application with the debugger and without the debugger. Can you see any differences? Try setting a breakpoint and play around with the debugger.

## 2. The first countdown

Use a `for` loop to create a countdown from 10 to 1. Each number should be displayed after a waiting time of 1 second. Realize that waiting period by using `Thread.Sleep(1000)` of the `System.Threading` namespace.

## 3. Currency converter

Write a little currency converter as a console application. The user should be asked to enter a value. Once a value has been entered the user is requested to enter a valid currency exchange rate. Afterwards the converted value should be displayed. Finally, if no error occurred, ask the user if another value should be converted. If yes, then start again by asking the user to enter a value. Otherwise exit the program.

#### 4. A simple calculator

Request the user to enter two numbers and an operation (`+`, `-` or `*`). Use a `switch` statement to perform the right computation. Display the result.

## 5. Computing prime numbers

The user has to enter some number, which should be evaluated by your program. If the program detects a non-positive, or invalid number, the program should exit. Otherwise the evaluation should display if the entered number has been a prime number or not. In case of not being a prime number, the program has to display all the prime factors of the given number.

## 6. Write a swap method

Write a simple method called `Swap()` to exchange to given integers. The method should work in such a way, that the following program works:

```int a = 0;
int b = 1;
//Calling Swap with a and b

if(a != 1 || b!= 0)
throw new Exception("Swap does not work yet!");

Console.WriteLine("Swap seems to work for this case!");
```

## 7. Guess a number

Write a guess-a-number game. The .NET random generator is available by generating a new instance of the `Random` class. The game should give the user the opportunity to enter the range of numbers. Based on this range the number of tries should be determined (you can decide how hard the game should be). For each try the user has the ability to guess a number. If the guessed number is the generated number, then the user won the game. If the number of tries has been exceeded, the user lost the game.

## 8. Simple numerical integration

Approximate the integral of a function by taking the sum of the areas of rectangles, i.e. compute

F=∫abf(x)dx≈ΔxΣif(xi).

Pack everything in a method called `Integrate`. This method should take 4 input parameters:

• A `double`, which represents the start of the integral a.
• A `double`, which represents the end of the integral b.
• An `int`, which represents the number of rectangles N.
• A `Func<double, double>`, which represents the function f.

Use your method to show that the value of the integral is becoming more precise as N increases.

## 9. Digit sum

Create a method, which has an `int` argument (called number) and an `out` of `int` argument (called digits). The return type should be an `int` as well.

This method would then compute the digit sum of all digits in the given number argument. The digits argument should be set to the number of given digits in number, while the result of the computation would be returned.

## 10. A useful class

Create a class, which simplifies receiving user input in the console. The class should have a default constructor and another constructor, which requires a `string` to be passed. The given `string` should be used as the message for the user the prompt. In case of the default constructor a default message should be displayed.

The class should have a method called `ParseInt()` and another method called `ParseDouble()`. The `ParseInt()` method will try to get a valid integer value. If no valid integer value is passed in, it will display an error message and prompt the user to enter a valid integer value. Once a valid integer value is passed in, this loop is broken and the value is returned. The `ParseDouble()` method does the same with a floating point value instead of an integer.

## 11. Extending existing classes

Create a class called `MyRandom`, which derives from the .NET class `Random`, but returns different values. Implement a new method called `Next()` and a possibility to access the `protected` method `Sample()` from outside.

## 12. A simple but useful structure

Create a structure called `Point3`, which contains 3 (private) `float` variables called x, y and z. Create a property for each variable. Changing a variable (setting it) should result in output on the console. The output has to tell us which variable changed and what changed (old value, new value).

Look up the syntax for overloading the addition operator `+` (look it up by viewing the meta data (definition) of e.g. the `decimal` structure). Implement it for your structure.

Finally use your structure in a new version of your calculator. This time not integers, but `Point3`s will be used.

## 13. Vehicle, Car, ...

Start by creating an `abstract` class called `Vehicle`. Create two `abstract` methods called `Accelerate()` and `Brake()`. Additionally you should place an (protected) integer variable called `tires`. Add a property called `Tire`, which defines a `get` block for the variable.

Derive a class called `Car` from `Vehicle`. Implement the two functions in such a way, that they display the state change like "The car is is driving" or "The car is braking" on the console. Additionally extend the class with an integer property called `Gears` (with `get` and `set`) and set the value of `tires` to 4.

Finally derive from `Car` and call the new class `Porsche`. Override the method `Drive()` with some string that might represent your attitude towards driving a Porsche.

## 14. Let's create a copy

Extend the class `Car` of assignment 13 with a copy-constructor, i.e. a constructor which takes an instance of the own class as input parameter, and uses this instance to create a (usually deep) copy of all fields.

Also override the method `Equals()` in a way that it is possible to compare one instance of the class `Car` with another for equality.

Finally try to cast an instance of your `Car` class to the `Porsche` class. Why is this not possible?

## 15. (MP) Write a class for (2D) plotting

Write a project that makes storing plot-data in C# objects possible. The project has to fulfill the following requirements:

• An arbitrary amount of data series should be storable.
• Each series consists of an arbitrary amount of data points.
• Each data point consists of an X and a Y value.
• Each series contains information about the min x and y, as well as max x and y values.
• Each series has a label and a color (just a string) assigned.

The project aims to be very generic, such that the created plotting class construct could be used with various renderes. A renderer is a special class, which takes some input, analyzes it and starts streaming some output in a certain form. In this case you could input an instance of your plotting class into some renderer, which would transform it to e.g. HTML output, displaying something on the console or a bitmap image.

## 16. Communication between Forms

Write a small Windows Forms application that consists of two windows (forms). The first (main) window should have a `ComboBox` with two values, "blocking" and "non-blocking", a `Button` and an empty `Label`.

The second window should have a `TextBox` and two `Button` controls, one with the text being "OK" and another one with the text being "Cancel".

Pressing the button in the main window should open the second window. If the value "blocking" has been selected from the `ComboBox` control, then the `ShowDialog()` method should be picked, otherwise the `Show()` method is the way to go.

The second window should be closed on pressing one of the buttons. The difference between the two buttons is, however, that the OK button does also "transmit" the value in textbox to the label of the main window.

## 17. Getting to know the .NET-Framework

Place a variety of controls on a `Form` and display some of the information you can read out using the `Environment` class like the current username and the current directory.

## 18. Reaction speed

Write a Windows Forms application that measures the reaction speed using the classes `Random`, `Timer` and `Stopwatch`. The `Timer` can be placed per drag and drop on the `Form` as a control.

First you use a random number to determine the value for the timer (when to display a label, that the button can now be pressed). Then, when the timer is firing it's elapsed event, start a new stopwatch measurement. Once the user presses the button the stopwatch should be stopped and the reaction time should be displayed.

## 19. A set of simple LINQ queries

Start by using the following LINQ query:

```var random = new Random();
var list = Enumerable.Range(0, 100).Select(m => random.Next(0, 1000)).ToArray();
```

Create now a set of new variables based on the variable list. In total create the following variables with LINQ:

• Find the minimum element min in list.
• Find the maximum element max in list.
• Save the ordered array as a `List<int>` in ordered.
• Save all odd elements of list in onlyodd.
• Take only the 10 elements after the first 15 elements and save them as an array in elements.
• Take the first element that is bigger than 999 and save it in hulk.

## 20. A custom user control

Create a custom user control that contains a `Timer` control and a `Label` control as well as a `Button`. The user control should do the following:

• Show the button with the text "Start" and the interval time of the timer.
• When the button is pressed the time string on the label should be updated.
• The button should be named "Stop" now until the timer finishes (tick event).
• The button should now display "Reset". If that is being pressed then the initial state should be shown again.

Implement a multithreaded program. One thread, the worker thread, is doing some time consuming "work" (i.e. counts to infinity) and reports periodically its progress to another thread, the UI thread.

A sample code for the worker thread (without reporting the progress) would be the following:

```//Ping is available in System.Net.NetworkInformation
Ping ping = new Ping();

//Replace true with a statement if the loop should continue
while (true)
{

//Use information from reply when reporting progress

//Just wait a bit before making sending again
}
```

One last thing: Avoid cross-threading exceptions!

## 22. (MP) Write a simple math tool

Write a simple math tool that let's users enter numbers in two textboxes. Only integer numbers separated by commas should be allowed. Place all user controls in a `TabControl`.

There should be one `ComboBox` element and one `Button` control. The combobox contains the following strings:

• Intersection
• Union
• Except
• Symmetric Except
• Square
• Square Root
• Sum
• Min
• Max

If the button is pressed a function is called depending on the currently selected item in the combobox. While the first four functions are requiring both sets of numbers (obtained from the two textboxes), the other functions only require one of the sets.

It should be obvious that each function represents a LINQ function. The result of the LINQ operation should be displayed in a new tab (called results) of your form.

## 23. Async / await with C# 5

Compute the following method in an async task and await the result:

```double ComputePi()
{
var sum = 0.0;
var step = 1e-9;

for(var i = 0; i < 1000000000; i++)
{
var x = (i + 0.5) * step;
sum = sum + 4.0 / (1.0 + x * x);
}

return sum * step;
}
```

Start the computation by presing a button. The button click event handler should then disable the button, await the result of the computation, set the result of the computation in a label and enable the button again.

## 24. The Task Parallel Library

Use the Task Parallel Library to make a parallel version of the method given in exercise 23. Try to avoid race conditions, i.e. synchronize the communication on shared variables. Reduce the required communication where possible and reduce the usage of shared variables to a minimum. Compare executation time and result with the serial implementation.

Hint Use `Parallel.For` instead of `for` and take the overload that defines a (thread-)local variable as well.

## 25. A little picture viewer

Use the `PictureBox` control, a `ComboBox` and a `FolderBrowserDialog` to create a simple application, which lets a user open a certain directory. All images of the selected directory (the following types are enough: png, gif, jpg, bmp) should be displayed in the combobox. Once the selected index of the combobox changes, the picture behind the selected item should be displayed in the picturebox.

As a little extra work you can try to implement a zoom and rotate operation.

Nowadays really simple note apps seem to be in fashion again. Write a small program that uses your own class called `Note`. An instance of `Note` contains a creation date, a last update date, a priority enumeration value (think about good values in this enumeration), a title, remark and description, as well as a due date. Dates should be saved as `DateTime`.

The application should be able to create new note instances, load existing notes from the file system and save notes to the file system. Use the `XmlSerializer` for loading and saving instances of the `Note` class. Use the `DateTimePicker` as the control for any `DateTime` value.

Hint Using the dialoges called `OpenFileDialog` and `SaveFileDialog` will help a lot.

## 27. Dynamic programming and webrequests

Create a method to read out XML files that have been placed on some webserver. In the first stage the content (XML) should be received. Afterwards, create a new instance of `XmlDocument` as a `dynamic` type.

Show that you can actually access the member of the XML document dynamically, i.e. that the following lines of code,

```var document = new XmlDocument("...");
var element = document.GetElement("root").GetElement("child");
```

could be replaced by the following code (in case of an XML document with a root node called root and a child node called child):

```dynamic document = new XmlDocument("...");
var element = document.root.child;
```

Show that `object`, `var` and `dynamic` are three different things.

The URL of a sample XML document is http://csharp.florian-rappl.de/samples/Books.xml.

## 28. Events

Extend the custom user control (exercise 20) with some events called

• Started,
• Stopped, passing the passed time and the reason (button pressed or time over) in the event arguments and
• Updated, passing the current time in the event arguments.

Create an event-handler for the `Updated` event in the code-behind (no-designer) and update the name of the form with the given information.

## 29. A simple paint program

Create a Windows Forms application that consists of a `PictureBox` control. Once the user presses the left mouse button a line is drawn.

Additionally integrate some buttons that let the user choose a color and thickness for drawing a line. Think about how you could implement drawing helpers like drawing rectangles, ellipses and more.

## 30. A plotting tool

Use the plotting class from exercise 15 to create a tool that will parse simple math expressions, evaluate them in a given interval and plot the results.

Create a user control that let's you re-use all the work done before. The user control will depend on your plotting class and should perform the drawing of the plot. The parsing should be done in another class that just expects a string to be given.

## 31. Your first dynamic webpage

Create a webpage with ASP.NET MVC 4. The `HomeController` should display a welcome page with an input box and a submit button on the `Index()` action. Once a user presses the submit button a page should be shown which displays the content of the input box.

## 32. A simple Windows Store app

Recreate your reaction time game as a Windows Store app. You can reuse your logic (maybe you can now improve it), but you will have to re-implement the UI. Use the designer for doing the redesigning.

## Solutions

[ 119 kB ]
Solutions for the exercises of the C# lecture.
Created . Last updated .