C# Exercises
Time to practise! Each exercise has a starter playground that already compiles and runs. Replace the TODO parts with your own code, press ▶ Run, and compare your result with the expected output described in the task. When you are done — or stuck — open the solution.
Tip: There are always several correct solutions. If your output matches, your answer is right, even if it looks different from ours.
Exercise 1: Temperature table
Print a table of Celsius temperatures from 0 to 100 in steps of 25, with the Fahrenheit value next to each (F = C × 9 / 5 + 32). Expected output:
0°C = 32°F
25°C = 77°F
50°C = 122°F
75°C = 167°F
100°C = 212°Fusing System;
// TODO: loop from 0 to 100 in steps of 25 and print each conversion
Console.WriteLine("0°C = 32°F");0°C = 32°F
Show solution
using System;
for (int c = 0; c <= 100; c += 25)
{
int f = c * 9 / 5 + 32;
Console.WriteLine(quot;{c}°C = {f}°F");
}Exercise 2: FizzBuzz
For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise. Print them on one line separated by spaces: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz.
using System;
for (int i = 1; i <= 15; i++)
{
// TODO: decide what to print
Console.Write(i + " ");
}
Console.WriteLine();1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
using System;
for (int i = 1; i <= 15; i++)
{
string text = (i % 3, i % 5) switch
{
(0, 0) => "FizzBuzz",
(0, _) => "Fizz",
(_, 0) => "Buzz",
_ => i.ToString()
};
Console.Write(text + " ");
}
Console.WriteLine();Exercise 3: Palindrome checker
Write a method IsPalindrome(string s) that ignores case, spaces and punctuation. "Never odd or even" and "A man, a plan, a canal: Panama" are palindromes; "C sharp" is not.
using System;
static bool IsPalindrome(string s)
{
// TODO: keep only letters/digits, lower-case them, compare with the reverse
return false;
}
foreach (string s in new[] { "Never odd or even", "A man, a plan, a canal: Panama", "C sharp" })
Console.WriteLine(quot;{s}: {IsPalindrome(s)}");Never odd or even: False
A man, a plan, a canal: Panama: False
C sharp: False
Show solution
using System;
using System.Text;
static bool IsPalindrome(string s)
{
var sb = new StringBuilder();
foreach (char c in s)
if (char.IsLetterOrDigit(c))
sb.Append(char.ToLower(c));
string clean = sb.ToString();
for (int i = 0, j = clean.Length - 1; i < j; i++, j--)
if (clean[i] != clean[j]) return false;
return true;
}
foreach (string s in new[] { "Never odd or even", "A man, a plan, a canal: Panama", "C sharp" })
Console.WriteLine(quot;{s}: {IsPalindrome(s)}");Exercise 4: Array statistics
Given an array of exam marks, print the minimum, maximum, average (2 decimals) and how many marks are above the average — without using LINQ. Expected: Min 48, Max 97, Average 73.88, Above average: 4.
using System;
int[] marks = { 72, 48, 97, 65, 81, 59, 90, 79 };
// TODO: compute min, max, average and the count above average
Console.WriteLine(quot;Marks: {marks.Length}");Marks: 8
Show solution
using System;
int[] marks = { 72, 48, 97, 65, 81, 59, 90, 79 };
int min = marks[0], max = marks[0], sum = 0;
foreach (int m in marks)
{
if (m < min) min = m;
if (m > max) max = m;
sum += m;
}
double average = (double)sum / marks.Length;
int above = 0;
foreach (int m in marks)
if (m > average) above++;
Console.WriteLine(quot;Min {min}, Max {max}, Average {average:F2}, Above average: {above}");Exercise 5: Word frequency
Count how often each word appears in the sentence (case-insensitive) and print the words that occur more than once, most frequent first. Expected output:
the: 4
fox: 2using System;
using System.Collections.Generic;
string sentence = "The quick fox jumps over the lazy dog and the fox sees the dog's owner";
var counts = new Dictionary<string, int>();
// TODO: split the sentence, count each lower-cased word, then print repeated words
Console.WriteLine(quot;Words: {sentence.Split(' ').Length}");Words: 15
Show solution
using System;
using System.Collections.Generic;
using System.Linq;
string sentence = "The quick fox jumps over the lazy dog and the fox sees the dog's owner";
var counts = new Dictionary<string, int>();
foreach (string word in sentence.ToLower().Split(' '))
counts[word] = counts.GetValueOrDefault(word) + 1;
foreach (var (word, count) in counts.Where(p => p.Value > 1).OrderByDescending(p => p.Value))
Console.WriteLine(quot;{word}: {count}");Exercise 6: Shapes with interfaces
Create an interface IShape with a method double Area(), and two classes Square and Circle that implement it. Then print the total area of a square with side 3 and a circle with radius 1, rounded to two decimals: Total area: 12.14.
using System;
// TODO: create IShape, Square and Circle, then sum their areas
double total = 0;
Console.WriteLine(quot;Total area: {total:F2}");Total area: 0.00
Show solution
using System;
IShape[] shapes = { new Square(3), new Circle(1) };
double total = 0;
foreach (IShape s in shapes)
total += s.Area();
Console.WriteLine(quot;Total area: {total:F2}");
interface IShape
{
double Area();
}
class Square : IShape
{
private readonly double side;
public Square(double side) => this.side = side;
public double Area() => side * side;
}
class Circle : IShape
{
private readonly double radius;
public Circle(double radius) => this.radius = radius;
public double Area() => Math.PI * radius * radius;
}Exercise 7: Safe parsing
The array contains user input. Parse each entry with int.TryParse; sum the valid numbers and count the invalid ones. Expected: Sum: 57, invalid entries: 3.
using System;
string[] inputs = { "12", "seven", "30", "", "15", "4.5" };
int sum = 0;
int invalid = 0;
// TODO: use int.TryParse for each input
Console.WriteLine(quot;Sum: {sum}, invalid entries: {invalid}");Sum: 0, invalid entries: 0
Show solution
using System;
string[] inputs = { "12", "seven", "30", "", "15", "4.5" };
int sum = 0;
int invalid = 0;
foreach (string input in inputs)
{
if (int.TryParse(input, out int value))
sum += value;
else
invalid++;
}
Console.WriteLine(quot;Sum: {sum}, invalid entries: {invalid}");Exercise 8: LINQ on records
Using the list of employees, print (a) the names of employees in the "IT" department sorted alphabetically and (b) the average salary per department, sorted by department name. Expected output:
IT: Ana, Femi, Jon
HR: 4100.00
IT: 5100.00
Sales: 3900.00using System;
using System.Collections.Generic;
using System.Linq;
var staff = new List<Employee>
{
new("Jon", "IT", 5200m), new("Mei", "HR", 4100m), new("Ana", "IT", 4800m),
new("Raj", "Sales", 3700m), new("Femi", "IT", 5300m), new("Ola", "Sales", 4100m),
};
// TODO: write the two LINQ queries
Console.WriteLine(quot;{staff.Count} employees");
record Employee(string Name, string Department, decimal Salary);6 employees
Show solution
using System;
using System.Collections.Generic;
using System.Linq;
var staff = new List<Employee>
{
new("Jon", "IT", 5200m), new("Mei", "HR", 4100m), new("Ana", "IT", 4800m),
new("Raj", "Sales", 3700m), new("Femi", "IT", 5300m), new("Ola", "Sales", 4100m),
};
var itNames = staff.Where(e => e.Department == "IT").Select(e => e.Name).OrderBy(n => n);
Console.WriteLine(quot;IT: {string.Join(", ", itNames)}");
foreach (var group in staff.GroupBy(e => e.Department).OrderBy(g => g.Key))
Console.WriteLine(quot;{group.Key}: {group.Average(e => e.Salary):F2}");
record Employee(string Name, string Department, decimal Salary);Test yourself
Which method safely converts user input to an int without throwing?
- int.Parse
- Convert.ToInt32
- int.TryParse
- (int)input
Which collection is the best fit for counting how often each word occurs?
- List<string>
- Dictionary<string, int>
- Stack<string>
- string[]