Tasks
All the tasks of the course in one place. First 50 standalone tasks from "Hello, World" to the shortest path in a grid, each with an example and a solution in C# checked with a real compiler. Then the tasks from the lessons, by module: each one leads to the lesson that explains what you need.
50 tasks to practise
1. Hello World
Print the text Hello, World! to the console; the program takes no input.
No input.
Output Hello, World!What you need is in the lesson: Your first program
Solution
class Program{static void Main(){Console.WriteLine("Hello, World!");}}2. Greet the user
Read a name from one line and greet the person by name as "Hello, <name>!".
Input MariaOutput Hello, Maria!What you need is in the lesson: Input and output
Solution
class Program{static void Main(){string name = Console.ReadLine();Console.WriteLine("Hello, " + name + "!");}}3. Print the age
Read the user's age (a whole number), store it in a variable and print it in a sentence.
Input 17Output You are 17 years old.What you need is in the lesson: Variables and types
Solution
class Program{static void Main(){int age = int.Parse(Console.ReadLine());Console.WriteLine("You are " + age + " years old.");}}4. Unit converter
Read a length in inches (it may be a decimal) and convert it to centimetres: 1 inch = 2.54 cm. Print the result with 2 decimal places.
Input 12.5Output 31.75 cmWhat you need is in the lesson: Operators and arithmetic
Solution
using System.Globalization;class Program{static void Main(){double inches = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);Console.WriteLine((inches * 2.54).ToString("F2", CultureInfo.InvariantCulture) + " cm");}}5. Even or odd
Read a whole number and print whether it is even or odd.
Input 7Output 7 is odd.What you need is in the lesson: Conditions
Solution
class Program{static void Main(){int number = int.Parse(Console.ReadLine());if (number % 2 == 0){Console.WriteLine(number + " is even.");}else{Console.WriteLine(number + " is odd.");}}}6. Sum of two numbers
Read two whole numbers, each on its own line, and print their sum.
Input 1230Output The sum is 42.What you need is in the lesson: Operators and arithmetic
Solution
class Program{static void Main(){int first = int.Parse(Console.ReadLine());int second = int.Parse(Console.ReadLine());Console.WriteLine("The sum is " + (first + second) + ".");}}7. Area of a square
Read the side of a square (a whole number) and print its area.
Input 5Output The area is 25.What you need is in the lesson: Operators and arithmetic
Solution
class Program{static void Main(){int side = int.Parse(Console.ReadLine());Console.WriteLine("The area is " + side * side + ".");}}8. Volume of a sphere
Read the radius r (it may be a decimal) and print the volume of the sphere V = 4/3 · π · r³ with 2 decimal places.
Input 3Output The volume is 113.10.What you need is in the lesson: Operators and arithmetic
Solution
using System.Globalization;class Program{static void Main(){double r = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);double volume = 4.0 / 3 * Math.PI * r * r * r;Console.WriteLine("The volume is " + volume.ToString("F2", CultureInfo.InvariantCulture) + ".");}}9. Compare two numbers
Read two whole numbers, each on its own line, and print the larger one (if they are equal, either will do).
Input 815Output The larger one is 15.What you need is in the lesson: Conditions
Solution
class Program{static void Main(){int a = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine());if (a > b){Console.WriteLine("The larger one is " + a + ".");}else{Console.WriteLine("The larger one is " + b + ".");}}}10. Triangle check
Read three whole numbers, each on its own line, and check whether they can be the sides of a triangle: any two of them must add up to more than the third.
Input 345Output They can form a triangle.What you need is in the lesson: Conditions
Solution
class Program{static void Main(){int a = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine());int c = int.Parse(Console.ReadLine());if (a + b > c && a + c > b && b + c > a){Console.WriteLine("They can form a triangle.");}else{Console.WriteLine("They cannot form a triangle.");}}}11. Grade to words
Read a mark on the Bulgarian scale from 2 to 6 (it may be a decimal) and print it in words: 5.50 and up is Excellent, 4.50 and up Very good, 3.50 and up Good, 3.00 and up Average, below 3.00 Poor.
Input 4.75Output Very goodWhat you need is in the lesson: Conditions
Solution
using System.Globalization;class Program{static void Main(){double grade = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);if (grade >= 5.5){Console.WriteLine("Excellent");}else if (grade >= 4.5){Console.WriteLine("Very good");}else if (grade >= 3.5){Console.WriteLine("Good");}else if (grade >= 3){Console.WriteLine("Average");}else{Console.WriteLine("Poor");}}}12. Hours to seconds
Read a number of hours (a whole number) and print how many seconds that is.
Input 2Output 7200 secondsWhat you need is in the lesson: Operators and arithmetic
Solution
class Program{static void Main(){int hours = int.Parse(Console.ReadLine());Console.WriteLine(hours * 3600 + " seconds");}}13. Count to N
Read a whole number N and print the numbers from 1 to N, each on a new line.
Input 5Output 12345What you need is in the lesson: Loops
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());for (int i = 1; i <= n; i++){Console.WriteLine(i);}}}14. ASCII value
Read one character (the first character of the line) and print its ASCII code, the number the computer stores it as.
Input AOutput The code of A is 65.What you need is in the lesson: Strings: working with text
Solution
class Program{static void Main(){char symbol = Console.ReadLine()[0];Console.WriteLine("The code of " + symbol + " is " + (int)symbol + ".");}}15. Quadratic equation
Read a, b and c, each on its own line, and solve ax² + bx + c = 0. With two roots print "x1 = …, x2 = …" (x1 uses +√D), with one root "x = …", with 2 decimal places; if there are no real roots or a is 0, say so.
Input 1-32Output x1 = 2.00, x2 = 1.00What you need is in the lesson: Conditions
Solution
using System.Globalization;class Program{static void Main(){double a = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);double b = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);double c = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);if (a == 0){Console.WriteLine("This is not a quadratic equation");}else{double d = b * b - 4 * a * c;if (d > 0){double x1 = (-b + Math.Sqrt(d)) / (2 * a);double x2 = (-b - Math.Sqrt(d)) / (2 * a);Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "x1 = {0:F2}, x2 = {1:F2}", x1, x2));}else if (d == 0){Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "x = {0:F2}", -b / (2 * a)));}else{Console.WriteLine("No real roots");}}}}16. Positive or negative
Read a whole number and print whether it is positive, negative or zero.
Input -4Output NegativeWhat you need is in the lesson: Conditions
Solution
class Program{static void Main(){int number = int.Parse(Console.ReadLine());if (number > 0){Console.WriteLine("Positive");}else if (number < 0){Console.WriteLine("Negative");}else{Console.WriteLine("Zero");}}}17. Seasons
Read a month number (1–12) and print its season: 12, 1, 2 are Winter, 3–5 Spring, 6–8 Summer, 9–11 Autumn. For any other number print "Invalid month".
Input 4Output SpringWhat you need is in the lesson: Conditions
Solution
class Program{static void Main(){int month = int.Parse(Console.ReadLine());if (month < 1 || month > 12){Console.WriteLine("Invalid month");}else if (month == 12 || month <= 2){Console.WriteLine("Winter");}else if (month <= 5){Console.WriteLine("Spring");}else if (month <= 8){Console.WriteLine("Summer");}else{Console.WriteLine("Autumn");}}}18. Reverse a number
Read a positive whole number and print the number with its digits in reverse order: 123 becomes 321. Zeros that end up in front disappear (1200 becomes 21). Take the last digit with % 10 and drop it by dividing by 10.
Input 9071Output 1709What you need is in the lesson: Loops
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());int reversed = 0;while (n > 0){reversed = reversed * 10 + n % 10;n /= 10;}Console.WriteLine(reversed);}}19. Temperature converter
Read a temperature in degrees Celsius (it may have a decimal point) and print it in Fahrenheit with two decimal places. The formula is F = C * 9 / 5 + 32.
Input 36.6Output 97.88 °FWhat you need is in the lesson: Operators and arithmetic
Solution
using System.Globalization;class Program{static void Main(){double celsius = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);double fahrenheit = celsius * 9 / 5 + 32;Console.WriteLine(fahrenheit.ToString("F2", CultureInfo.InvariantCulture) + " °F");}}20. Longest name
The first line holds the number of names n, and each of the next n lines holds one name. Print the name with the most letters and their count in brackets; if two names are equally long, print the first of them.
Input 4MiaAlexandraJohnCharlotteOutput Alexandra (9 letters)What you need is in the lesson: Strings: working with text
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());string longest = "";for (int i = 0; i < n; i++){string name = Console.ReadLine();if (name.Length > longest.Length){longest = name;}}Console.WriteLine($"{longest} ({longest.Length} letters)");}}21. Word counter
Read one line of text and print how many words it has. Words are separated by one or more spaces, so the empty pieces between two spaces are not words.
Input I write code every day and get betterOutput 8What you need is in the lesson: Strings: working with text
Solution
class Program{static void Main(){string line = Console.ReadLine();string[] words = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);Console.WriteLine(words.Length);}}22. Prime number
Read a whole number n and check whether it is prime: greater than 1 and divisible only by 1 and itself. It is enough to try the divisors i for which i * i <= n.
Input 91Output 91 is not primeWhat you need is in the lesson: Loops
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());bool prime = n > 1;for (int i = 2; i * i <= n; i++){if (n % i == 0){prime = false;break;}}if (prime){Console.WriteLine(n + " is prime");}else{Console.WriteLine(n + " is not prime");}}}23. Day of the week
Read a number from 1 to 7 and print the name of that day of the week, where 1 is Monday. Keep the names in an array; for any other number print "No such day".
Input 5Output FridayWhat you need is in the lesson: Arrays
Solution
class Program{static void Main(){int day = int.Parse(Console.ReadLine());string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };if (day >= 1 && day <= 7){Console.WriteLine(days[day - 1]);}else{Console.WriteLine("No such day");}}}24. Factorial
Read a whole number n from 0 to 15 and print n! = 1 * 2 * ... * n (0! is 1). Already 13! does not fit in an int, so in Java and C# keep the product in a long.
Input 15Output 15! = 1307674368000What you need is in the lesson: Loops
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());long factorial = 1;for (int i = 2; i <= n; i++){factorial *= i;}Console.WriteLine($"{n}! = {factorial}");}}25. Valid date
Read a day, a month and a year, each on its own line, and print "Valid date" or "Invalid date". The year is at least 1, the month is from 1 to 12 and the day from 1 to the number of days in that month; February has 29 days in a leap year (divisible by 4 but not by 100, unless it is divisible by 400).
Input 2922100Output Invalid dateWhat you need is in the lesson: Conditions
Solution
class Program{static void Main(){int day = int.Parse(Console.ReadLine());int month = int.Parse(Console.ReadLine());int year = int.Parse(Console.ReadLine());bool leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;int days;if (month == 2){days = leap ? 29 : 28;}else if (month == 4 || month == 6 || month == 9 || month == 11){days = 30;}else{days = 31;}if (year >= 1 && month >= 1 && month <= 12 && day >= 1 && day <= days){Console.WriteLine("Valid date");}else{Console.WriteLine("Invalid date");}}}26. Letter frequency
Read one line of text and print how many times each letter appears in it, ignoring upper and lower case. Print the letters in alphabetical order, one per line, as "a: 5"; spaces and punctuation are not counted.
Input Hello, World!Output d: 1e: 1h: 1l: 3o: 2r: 1w: 1What you need is in the lesson: Dictionary and HashSet
Solution
class Program{static void Main(){string text = Console.ReadLine().ToLower();SortedDictionary<char, int> counts = new SortedDictionary<char, int>();foreach (char c in text){if (char.IsLetter(c)){counts[c] = counts.GetValueOrDefault(c, 0) + 1;}}foreach (KeyValuePair<char, int> pair in counts){Console.WriteLine($"{pair.Key}: {pair.Value}");}}}27. Minimum and maximum in an array
The first line holds the count n, and each of the next n lines holds one whole number. Read them into an array and print the smallest and the largest, starting from the first element and comparing it with the rest.
Input 57-31204Output Smallest: -3Largest: 12What you need is in the lesson: Arrays
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());int[] numbers = new int[n];for (int i = 0; i < n; i++){numbers[i] = int.Parse(Console.ReadLine());}int min = numbers[0];int max = numbers[0];for (int i = 1; i < n; i++){if (numbers[i] < min){min = numbers[i];}if (numbers[i] > max){max = numbers[i];}}Console.WriteLine("Smallest: " + min);Console.WriteLine("Largest: " + max);}}28. Sort an array
The first line holds the count n, and each of the next n lines holds one whole number. Sort them yourself in ascending order with bubble sort (n - 1 passes, each swapping neighbours that are in the wrong order) and print them on one line, separated by spaces.
Input 6529156Output 1 2 5 5 6 9What you need is in the lesson: Arrays
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());int[] numbers = new int[n];for (int i = 0; i < n; i++){numbers[i] = int.Parse(Console.ReadLine());}for (int pass = 0; pass < n - 1; pass++){for (int i = 0; i < n - 1 - pass; i++){if (numbers[i] > numbers[i + 1]){int temp = numbers[i];numbers[i] = numbers[i + 1];numbers[i + 1] = temp;}}}Console.WriteLine(string.Join(" ", numbers));}}29. Replace the vowels
Read one line of text and print it with every vowel, upper or lower case, replaced by the character *. The vowels are a, e, i, o, u.
Input I love programmingOutput * l*v* pr*gr*mm*ngWhat you need is in the lesson: Strings: working with text
Solution
class Program{static void Main(){string text = Console.ReadLine();string vowels = "aeiou";string result = "";foreach (char c in text){if (vowels.Contains(char.ToLower(c))){result += "*";}else{result += c;}}Console.WriteLine(result);}}30. Sum of the digits
Read a whole non-negative number and print the sum of its digits. The last digit is n % 10, and n / 10 drops it (n // 10 in Python).
Input 9875Output 29What you need is in the lesson: Loops
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());int sum = 0;while (n > 0){sum += n % 10;n /= 10;}Console.WriteLine(sum);}}31. Palindrome
Read one line of text and check whether it is a palindrome, that is, it reads the same backwards. Upper and lower case count as the same and spaces are skipped. Print "Palindrome" or "Not a palindrome".
Input Never odd or evenOutput PalindromeWhat you need is in the lesson: Strings: working with text
Solution
class Program{static void Main(){string text = Console.ReadLine().ToLower().Replace(" ", "");bool palindrome = true;for (int i = 0; i < text.Length / 2; i++){if (text[i] != text[text.Length - 1 - i]){palindrome = false;break;}}if (palindrome){Console.WriteLine("Palindrome");}else{Console.WriteLine("Not a palindrome");}}}32. Strong password
Read passwords, one per line, until a strong one arrives: at least 8 characters, at least one digit, one uppercase and one lowercase letter. For each weak one print the first rule it breaks, in this order ("Too short", "No digit", "No uppercase letter", "No lowercase letter"); for the strong one print "Password accepted" and stop.
Input kotkakotkamiaukotkamiau7Kotkamiau7Output Too shortNo digitNo uppercase letterPassword acceptedWhat you need is in the lesson: Strings: working with text
Solution
class Program{static void Main(){while (true){string password = Console.ReadLine();bool digit = false;bool upper = false;bool lower = false;foreach (char c in password){if (char.IsDigit(c)){digit = true;}else if (char.IsUpper(c)){upper = true;}else if (char.IsLower(c)){lower = true;}}if (password.Length < 8){Console.WriteLine("Too short");}else if (!digit){Console.WriteLine("No digit");}else if (!upper){Console.WriteLine("No uppercase letter");}else if (!lower){Console.WriteLine("No lowercase letter");}else{Console.WriteLine("Password accepted");break;}}}}33. Reverse an array
The first line holds the count n, and each of the next n lines holds one whole number. Read them into an array and print them in reverse order on one line, separated by spaces: walk the array from the last index down to zero.
Input 410-273Output 3 7 -2 10What you need is in the lesson: Arrays
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());int[] numbers = new int[n];for (int i = 0; i < n; i++){numbers[i] = int.Parse(Console.ReadLine());}for (int i = n - 1; i >= 0; i--){Console.Write(numbers[i]);if (i > 0){Console.Write(" ");}}Console.WriteLine();}}34. Count the elements
Read one line of words separated by single spaces and print how many times each word appears, as "word: count". The words come out in the order in which they first appeared.
Input apple pear apple plum pear appleOutput apple: 3pear: 2plum: 1What you need is in the lesson: Dictionary and HashSet
Solution
class Program{static void Main(){string line = Console.ReadLine();Dictionary<string, int> counts = new Dictionary<string, int>();foreach (string word in line.Split(' ')){counts[word] = counts.GetValueOrDefault(word, 0) + 1;}foreach (KeyValuePair<string, int> pair in counts){Console.WriteLine($"{pair.Key}: {pair.Value}");}}}35. Prime numbers
Read a number N and print all prime numbers from 2 to N on one line, separated by spaces.
Input 30Output 2 3 5 7 11 13 17 19 23 29What you need is in the lesson: Loops
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());string result = "";for (int i = 2; i <= n; i++){bool prime = true;for (int d = 2; d * d <= i; d++){if (i % d == 0){prime = false;break;}}if (prime){result += i + " ";}}Console.WriteLine(result.Trim());}}36. Average
One line holds whole numbers separated by spaces. Print their average with two digits after the decimal point.
Input 5 8 12 6Output Average: 7.75What you need is in the lesson: Arrays
Solution
using System.Globalization;class Program{static void Main(){string[] parts = Console.ReadLine().Split(' ');int sum = 0;for (int i = 0; i < parts.Length; i++){sum += int.Parse(parts[i]);}double average = (double)sum / parts.Length;Console.WriteLine("Average: " + average.ToString("F2", CultureInfo.InvariantCulture));}}37. Sort by length
One line holds words separated by spaces. Sort them by length from shortest to longest (words of equal length keep their input order) and print them on one line.
Input cherry fig banana kiwi plumOutput fig kiwi plum cherry bananaWhat you need is in the lesson: Strings: working with text
Solution
class Program{static void Main(){string[] words = Console.ReadLine().Split(' ');for (int i = 0; i < words.Length - 1; i++){for (int j = 0; j < words.Length - 1 - i; j++){if (words[j].Length > words[j + 1].Length){string temp = words[j];words[j] = words[j + 1];words[j + 1] = temp;}}}Console.WriteLine(string.Join(" ", words));}}38. Sentence counter
Read one line of text and print how many sentences it has. A sentence ends with a full stop, an exclamation mark or a question mark; a run of such marks (like "..." or "?!") is a single ending.
Input Hi! How are you? I am fine... And you?!Output Sentences: 4What you need is in the lesson: Strings: working with text
Solution
class Program{static void Main(){string text = Console.ReadLine();string ends = ".!?";int count = 0;for (int i = 0; i < text.Length; i++){bool isEnd = ends.Contains(text[i]);bool nextIsEnd = i + 1 < text.Length && ends.Contains(text[i + 1]);if (isEnd && !nextIsEnd){count++;}}Console.WriteLine("Sentences: " + count);}}39. Fibonacci numbers
The Fibonacci sequence starts with 1, 1, and every next number is the sum of the previous two. Read N (from 1 to 50) and print the N-th number of the sequence.
Input 40Output 102334155What you need is in the lesson: Loops
Solution
class Program{static void Main(){int n = int.Parse(Console.ReadLine());long previous = 0;long current = 1;for (int i = 1; i < n; i++){long next = previous + current;previous = current;current = next;}Console.WriteLine(current);}}40. Finding the median
One line holds whole numbers separated by spaces. Print their median with one digit after the decimal point: the middle number once they are sorted, or the mean of the two middle ones when the count is even.
Input 12 3 7 9 1 8Output Median: 7.5What you need is in the lesson: Lists
Solution
using System.Globalization;class Program{static void Main(){List<int> numbers = new List<int>();foreach (string part in Console.ReadLine().Split(' ')){numbers.Add(int.Parse(part));}numbers.Sort();int n = numbers.Count;double median;if (n % 2 == 1){median = numbers[n / 2];}else{median = (numbers[n / 2 - 1] + numbers[n / 2]) / 2.0;}Console.WriteLine("Median: " + median.ToString("F1", CultureInfo.InvariantCulture));}}41. Character chart
Read one line of text. For every character except the space, in order of first appearance, print a line "character | stars" with one star for each time it occurs in the text.
Input banana breadOutput b | **a | ****n | **r | *e | *d | *What you need is in the lesson: Strings: working with text
Solution
class Program{static void Main(){string text = Console.ReadLine();for (int i = 0; i < text.Length; i++){char c = text[i];if (c != ' ' && text.IndexOf(c) == i){int count = 0;for (int j = 0; j < text.Length; j++){if (text[j] == c){count++;}}Console.WriteLine(c + " | " + new string('*', count));}}}}42. Transposing a matrix
The first line holds the number of rows R and columns C, followed by R lines of C numbers separated by spaces. Print the transposed matrix: C lines of R numbers, where rows become columns.
Input 2 31 2 34 5 6Output 1 42 53 6What you need is in the lesson: Two-dimensional arrays
Solution
class Program{static void Main(){string[] size = Console.ReadLine().Split(' ');int rows = int.Parse(size[0]);int cols = int.Parse(size[1]);int[,] matrix = new int[rows, cols];for (int r = 0; r < rows; r++){string[] parts = Console.ReadLine().Split(' ');for (int c = 0; c < cols; c++){matrix[r, c] = int.Parse(parts[c]);}}for (int c = 0; c < cols; c++){string line = "";for (int r = 0; r < rows; r++){line += matrix[r, c] + " ";}Console.WriteLine(line.Trim());}}}43. Paths in a maze
The first line holds R and C, followed by R lines of C characters: "." is a free cell and "#" is a wall. Moving only right or down and never stepping on a wall, print the number of all paths from the top-left to the bottom-right corner.
Input 4 5......#.#....#.#....Output Paths: 4What you need is in the lesson: Recursion
Solution
class Program{static int CountPaths(string[] maze, int r, int c){if (r >= maze.Length || c >= maze[0].Length || maze[r][c] == '#'){return 0;}if (r == maze.Length - 1 && c == maze[0].Length - 1){return 1;}return CountPaths(maze, r + 1, c) + CountPaths(maze, r, c + 1);}static void Main(){string[] size = Console.ReadLine().Split(' ');int rows = int.Parse(size[0]);string[] maze = new string[rows];for (int r = 0; r < rows; r++){maze[r] = Console.ReadLine();}Console.WriteLine("Paths: " + CountPaths(maze, 0, 0));}}44. Grade statistics
One line holds grades from 2 to 6 (the Bulgarian school scale, 6 is best), separated by spaces. Print how many are excellent, very good, good, satisfactory and poor, each category on its own line.
Input 6 4 5 6 3 5 2 6 5 4Output Excellent (6): 3Very good (5): 3Good (4): 2Satisfactory (3): 1Poor (2): 1What you need is in the lesson: Arrays
Solution
class Program{static void Main(){string[] names = { "", "", "Poor", "Satisfactory", "Good", "Very good", "Excellent" };int[] counts = new int[7];string[] parts = Console.ReadLine().Split(' ');for (int i = 0; i < parts.Length; i++){counts[int.Parse(parts[i])]++;}for (int grade = 6; grade >= 2; grade--){Console.WriteLine(names[grade] + " (" + grade + "): " + counts[grade]);}}}45. Roman numerals
Read a whole number from 1 to 3999 and print it in Roman numerals (I, V, X, L, C, D, M, where 4 is IV, 9 is IX, 40 is XL and so on).
Input 1994Output MCMXCIVWhat you need is in the lesson: Arrays
Solution
class Program{static void Main(){int number = int.Parse(Console.ReadLine());int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };string[] symbols = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };string roman = "";for (int i = 0; i < values.Length; i++){while (number >= values[i]){roman += symbols[i];number -= values[i];}}Console.WriteLine(roman);}}46. Coin toss simulation
Read a seed x (from 1 to 2147483646) and a number of tosses N, each on its own line. On every toss set x = x * 16807 % 2147483647; an even x is heads (H), an odd x is tails (T). Print the tosses on one line, then how many heads and how many tails came up.
Input 4210Output HTTTHTTHHTHeads: 4Tails: 6What you need is in the lesson: Loops
Solution
class Program{static void Main(){long x = long.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());string tosses = "";int heads = 0;for (int i = 0; i < n; i++){x = x * 16807 % 2147483647;if (x % 2 == 0){tosses += "H";heads++;}else{tosses += "T";}}Console.WriteLine(tosses);Console.WriteLine("Heads: " + heads);Console.WriteLine("Tails: " + (n - heads));}}47. Symmetric array
One line holds whole numbers separated by spaces. Check whether the array is symmetric, that is, it reads the same from left to right and from right to left.
Input 1 2 3 2 1Output SymmetricWhat you need is in the lesson: Arrays
Solution
class Program{static void Main(){string[] parts = Console.ReadLine().Split(' ');int[] numbers = new int[parts.Length];for (int i = 0; i < parts.Length; i++){numbers[i] = int.Parse(parts[i]);}bool symmetric = true;for (int i = 0; i < numbers.Length / 2; i++){if (numbers[i] != numbers[numbers.Length - 1 - i]){symmetric = false;break;}}Console.WriteLine(symmetric ? "Symmetric" : "Not symmetric");}}48. Balanced brackets
Read one line of text and check whether its brackets (), [] and {} are balanced: every opening bracket has a closing one of the same kind and the pairs do not cross. Other characters are ignored.
Input (a + [b) * c]Output Not balancedWhat you need is in the lesson: Stack, queue and linked list
Solution
class Program{static void Main(){string text = Console.ReadLine();string opening = "([{";string closing = ")]}";Stack<char> stack = new Stack<char>();bool balanced = true;foreach (char c in text){if (opening.Contains(c)){stack.Push(c);}else if (closing.Contains(c)){if (stack.Count == 0 || opening.IndexOf(stack.Pop()) != closing.IndexOf(c)){balanced = false;break;}}}if (balanced && stack.Count == 0){Console.WriteLine("Balanced");}else{Console.WriteLine("Not balanced");}}}49. Run of equal elements
One line holds whole numbers separated by spaces. Find the longest run of equal neighbouring numbers and print it on one line; if several runs have the same length, print the first one.
Input 2 1 1 3 3 3 2 2 2 5Output 3 3 3What you need is in the lesson: Arrays
Solution
class Program{static void Main(){string[] parts = Console.ReadLine().Split(' ');int[] numbers = new int[parts.Length];for (int i = 0; i < parts.Length; i++){numbers[i] = int.Parse(parts[i]);}int bestValue = numbers[0];int bestLength = 1;int length = 1;for (int i = 1; i < numbers.Length; i++){if (numbers[i] == numbers[i - 1]){length++;}else{length = 1;}if (length > bestLength){bestLength = length;bestValue = numbers[i];}}string result = "";for (int i = 0; i < bestLength; i++){result += bestValue + " ";}Console.WriteLine(result.Trim());}}50. Shortest path in a grid
The first line holds R and C, followed by R lines of C characters: "." is a free cell, "#" is a wall, "S" is the start and "E" is the goal. Moving up, down, left and right, print the smallest number of moves from S to E, or "No path" if E cannot be reached.
Input 5 6S.#....##.#....#..#.#..#...E.#Output 7What you need is in the lesson: Stack, queue and linked list
Solution
class Program{static void Main(){string[] size = Console.ReadLine().Split(' ');int rows = int.Parse(size[0]);int cols = int.Parse(size[1]);string[] grid = new string[rows];for (int r = 0; r < rows; r++){grid[r] = Console.ReadLine();}int[,] dist = new int[rows, cols];Queue<int[]> queue = new Queue<int[]>();for (int r = 0; r < rows; r++){for (int c = 0; c < cols; c++){dist[r, c] = -1;if (grid[r][c] == 'S'){dist[r, c] = 0;queue.Enqueue(new int[] { r, c });}}}int[] dr = { -1, 1, 0, 0 };int[] dc = { 0, 0, -1, 1 };string answer = "No path";while (queue.Count > 0){int[] cell = queue.Dequeue();int r = cell[0];int c = cell[1];if (grid[r][c] == 'E'){answer = dist[r, c].ToString();break;}for (int d = 0; d < 4; d++){int nr = r + dr[d];int nc = c + dc[d];if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] != '#' && dist[nr, nc] == -1){dist[nr, nc] = dist[r, c] + 1;queue.Enqueue(new int[] { nr, nc });}}}Console.WriteLine(answer);}}
Tasks from the lessons
Section titled "Tasks from the lessons"Language basics
- Your first program: Hello World · Business card · Frame
- Variables and types: Swap · Age · A hotel card
- Input and output: Greeting by name · Sum of two numbers · Two texts in one · π with two digits
- Operators and arithmetic: Average of three numbers · Seconds into hours · Volume of a sphere · Celsius to Fahrenheit
- Conditions: A cinema ticket · A mini calculator · A quadratic equation · A valid date
- Loops: Multiplication table · Prime number · The digits of a number · Guess the number
- Arrays: Sum, even, odd · Reversed · Lowest, highest, average
- Arrays: Sorting · Longest run · Grade statistics
- Two-dimensional arrays: Diagonals and rows · Flip the table
- Two-dimensional arrays: How many paths are there? · The shortest path
- Strings: working with text: The name backward · Word count · Palindrome
- Strings: working with text: Strong password
Methods
- Methods: Receipt · Triangle
- Parameters and return: Average · Prime number · Temperatures · Calculator · A triangle with a parameter
- Parameters and return
- Overloading: The largest · Average grade · A receipt line
- Recursion: Factorial two ways · Sum of digits · Fibonacci · Palindrome
Classes and objects
- Classes and objects: Book · Car · The cart · Most expensive first
- Constructors and this: Person · Animal · Dance move
- Instance methods
- Instance methods
- Encapsulation: Person · An account with no minus · Animal
- static: what all objects share: Orders · Calculator · Exchange
Inheritance and polymorphism
- Inheritance: Family car · Student · Breakdance · Electric car
- Polymorphism: Animal shelter · The student introduces themselves · Party
- Abstract classes: Area and perimeter · Animals
- Abstract classes: Vehicles · Performances
- Interfaces: Horn · Details · Dance · DJ · The pond
- Type checks: Parking lot · Dances · Fleet · Zoo
- OOP principles
- OOP principles: A contractor · The terrace without if
Errors and exceptions
- Exceptions: Text to number · No such product · Average order
- try, catch and finally: Price per person · Calculator
- Throwing and your own exceptions: Music shop · An account with rules · Invalid age
Collections
- Lists: A bookshelf · An event log · A notebook · Mental math
- Stack, queue and linked list: A toy train · A bus route · A stock ticker · Balanced brackets · Your own linked list
- Dictionary and HashSet: A user table · Word frequency · Documents by keyword · A contact network
- Hash codes and hash functions: A hash code for a person · The robot in the warehouse · A hash of a file
- Nested classes: Shopping cart · Web server monitor · Building manager · Ranking
Modern C#
- Lambdas and delegates: Sorting by several fields · Filtering orders · Discounts one after another
- LINQ: Sales by category · Top 3 products · Average grade · The words in a text
- record, switch and patterns: Shapes · Delivery price · A point as a key
- Design patterns: Discounts as strategies · "Notify me when it is in stock" · A notification factory · An old thermometer
Real-world programs
- Tests with xUnit: The discount calculator · The account · The bug in the average grade
- Threads: Parallel sum · Downloading with a pool · A counter without losses
- Network programming: Echo server · A server with commands · A chat for two
- Databases: Catalog · Search by part of the name · A transfer that fails halfway
- Reflection and attributes: All the properties · Mini JSON · Your own test runner
Web and desktop
- Lists, dictionaries and LINQ: Cart · Stock · Report
- async and await: One after another and at the same time · A refused request
- How the internet works: Parts of an address · What the status means · Build a request
- A web server with Minimal API: What time is it · A catalog with search · A missing product · Add a product
- MVC: model, view, controller: Catalog · Redirect after saving · Products by category
- Views with Razor: A product table · A shared layout with a menu · Booking a tasting
- WebAPI: data for other programs
- Windows with WPF: A bill with a tip · Tasks for the day · A currency converter
Let's make a game
- How to think about a game: A race for two · Guess the number · Who won at tic-tac-toe?
- RPG 1: the heroes: A sixth hero · The party roster · Who is the strongest?
- RPG 2: the battle: A new monster · A healing potion · A battle report
- RPG 3: the whole game: A menu · Progress · A boss
- Epic Cosmos 1: the objects in space: The solar system · Distance · The whole tree
- Epic Cosmos 2: resources, buildings, ships: 100 metal as fast as possible · A cargo ship · A 10-turn simulation
- The locked lab 1: rooms and commands: Inventory · A new room · Synonyms
- The locked lab 2: puzzles and the way out: The dark cellar · A timer · A hint for a move
Chronicles of Arcanum
- The game loop
- A stack of screens
- Screens that return an answer
- Drawing in the console
- The map and line of sight
- Heroes, enemies, stats
- The combat system
- Blood, wounds and effects
- Skills and actions as commands
- Enemies that think
- Items, inventory, loot
- Levels, dialogs and quests
- Saving and loading
- The whole game and the balance
Epic Cosmos: the empire
- The galaxy from a seed
- The technology tree
- Fleets and space battle
- The rivals
- The turn of the galaxy
- The whole strategy
Project
- Hotel reservations: Changing rooms