If you are just starting out with C#, the fastest way to get comfortable with the language is to write a lot of small programs. This collection of 58 beginner-friendly C# exercises takes you from your very first Console.WriteLine() statement all the way through variables, arithmetic, conditionals, loops, arrays, basic object-oriented programming, and simple file handling.
Each exercise includes a Practice Problem, a explanation of Purpose, a Hint, and a full Solution with Explanation, so you understand not just what the code does, but why it’s written that way.
Also, See: C# Exercises with 22 topic-wise sets and 620+ practice questions.
What You’ll Practice
- Fundamentals: Console input/output, variables, arithmetic operators, and string interpolation.
- Control Flow:
if/elseconditions,for/whileloops, and nested loops. - Basic Collections: Arrays, List, Strings, Dictionary
- OOP Basics: Classes, constructors, encapsulation, inheritance, structs, and records.
+ Table Of Contents (58 Exercises)
Table of contents
- Exercise 1: User Greeting
- Exercise 2: Sum of Two Numbers
- Exercise 3: Basic Calculator
- Exercise 4: Temperature Converter
- Exercise 5: Average Calculator
- Exercise 6: Remainder Finder
- Exercise 7: Days to Years/Weeks
- Exercise 8: Even or Odd
- Exercise 9: Swap Two Numbers
- Exercise 10: Simple Interest Calculator
- Exercise 11: Find the Maximum
- Exercise 12: Leap Year Checker
- Exercise 13: Uppercase Converter
- Exercise 14: Count Characters
- Exercise 15: Count to Ten
- Exercise 16: Countdown
- Exercise 17: Multiplication Table
- Exercise 18: Sum of N Numbers
- Exercise 19: Factorial Calculator
- Exercise 20: Even Numbers Only
- Exercise 21: Array Initialization
- Exercise 22: Find Min/Max in Array
- Exercise 23: Array Reverser
- Exercise 24: Sum of Array Elements
- Exercise 25: Search an Element
- Exercise 26: Dynamic Integer List
- Exercise 27: Remove Duplicates
- Exercise 28: String Reverser
- Exercise 29: Is Prime Function
- Exercise 30: Create a Car Class
- Exercise 31: Class Methods
- Exercise 32: Constructors
- Exercise 33: Bank Account Encapsulation
- Exercise 34: Basic Inheritance
- Exercise 35: The Point Struct
- Exercise 36: Immutable Color Struct
- Exercise 37: Product Record
- Exercise 38: Updating Records (with Expression)
- Exercise 39: Dynamic Grocery List (List<T>)
- Exercise 40: Contact Directory (Dictionary<TKey, TValue>)
- Exercise 41: Unique Registration (HashSet<T>)
- Exercise 42: Undo Mechanism (Stack<T>)
- Exercise 43: Customer Service Line (Queue<T>)
- Exercise 44: Sorted Inventory (SortedList<TKey, TValue>)
- Exercise 45: Key-Value Iteration
- Exercise 46: Collection Clearing & Checking
- Exercise 47: Filtering Even Numbers
- Exercise 48: Top Scorers
- Exercise 49: String Transformation (.Select())
- Exercise 50: Aggregation (Min, Max, Average)
- Exercise 51: Find the First Match
- Exercise 52: Digital Clock/Current Time
- Exercise 53: Age Calculator
- Exercise 54: Adding/Subtracting Time
- Exercise 55: Days in a Month
- Exercise 56: Diary Entry (Write Text)
- Exercise 57: Log Append
- Exercise 58: Diary Reader (Read Text)
Exercise 1: User Greeting
Practice Problem: Write a C# program that accepts a user’s name using Console.ReadLine() and prints a personalized greeting.
Purpose: This exercise helps you practice reading input from the console and combining it with text using string interpolation, a fundamental skill for building interactive command-line programs.
Given Input: Alice (entered by the user when prompted)
Expected Output: Hello, Alice! Welcome.
▼ Hint
- Use
Console.Write()orConsole.WriteLine()to display a prompt asking for the name. - Use
Console.ReadLine()to capture the input and store it in astringvariable. - Use string interpolation with a
$prefix to insert the variable into your greeting message.
▼ Solution & Explanation
Explanation:
namespace UserGreetingApplication: Groups the program’s code under a named container, following standard C# project structure.static void Main(string[] args): The entry point of the program. Execution starts here when the application runs.Console.Write("Enter your name: "): Displays a prompt without moving to a new line, so the user can type right after it.Console.ReadLine(): Reads the text typed by the user and returns it as astring, which is stored in thenamevariable.$"Hello, {name}! Welcome.": Uses string interpolation to insert the value ofnamedirectly into the output message.
Exercise 2: Sum of Two Numbers
Practice Problem: Declare two integer variables, add them together, and print the result.
Purpose: This exercise helps you practice declaring variables, performing basic arithmetic, and displaying results, the building blocks of nearly every C# program.
Given Input: firstNumber = 15, secondNumber = 27
Expected Output: Sum = 42
▼ Hint
Declare two int variables, add them using the + operator, and store the result in a third variable before printing it.
▼ Solution & Explanation
Explanation:
int firstNumber = 15; int secondNumber = 27;: Declares two integer variables and assigns them initial values.int sum = firstNumber + secondNumber;: Adds the two variables using the+operator and stores the result in a new variable.Console.WriteLine($"Sum = {sum}");: Uses string interpolation to print the label together with the calculated result.
Exercise 3: Basic Calculator
Practice Problem: Declare two numbers and display their sum, difference, product, and quotient.
Purpose: This exercise helps you practice using multiple arithmetic operators in one program and formatting several results for clear output.
Given Input: firstNumber = 20, secondNumber = 4
Expected Output:
Sum = 24 Difference = 16 Product = 80 Quotient = 5
▼ Hint
- Use
+,-,*, and/on the same two variables. - Store each result in its own variable before printing so the code stays readable.
- Use
Console.WriteLine()once for each result to print them on separate lines.
▼ Solution & Explanation
Explanation:
int sum = firstNumber + secondNumber;: Adds the two numbers together.int difference = firstNumber - secondNumber;: SubtractssecondNumberfromfirstNumber.int product = firstNumber * secondNumber;: Multiplies the two numbers using the*operator.int quotient = firstNumber / secondNumber;: DividesfirstNumberbysecondNumber. Since both are integers, this performs integer division.
Exercise 4: Temperature Converter
Practice Problem: Convert a temperature from Celsius to Fahrenheit.
Purpose: This exercise helps you practice applying a mathematical formula in code and working with floating-point arithmetic, useful for building real-world conversion utilities.
Given Input: celsius = 25
Expected Output: 25°C = 77°F
▼ Hint
- The formula for conversion is
F = (C * 9 / 5) + 32. - Use a
doublefor the Fahrenheit result to avoid losing precision. - Multiply by
9.0instead of9so the division is not truncated as integer math.
▼ Solution & Explanation
Explanation:
double celsius = 25;: Stores the input temperature as adoubleto support decimal precision.(celsius * 9.0 / 5.0) + 32: Applies the Celsius-to-Fahrenheit formula. Using9.0and5.0ensures floating-point division instead of integer division.$"{celsius}°C = {fahrenheit}°F": Uses string interpolation to display both values in a single readable line.
Exercise 5: Average Calculator
Practice Problem: Declare three decimal numbers (double) and print their mathematical average.
Purpose: This exercise helps you practice working with the double type and combining arithmetic operations to compute an average, a common calculation in reporting and analysis tasks.
Given Input: firstNumber = 10.5, secondNumber = 20.3, thirdNumber = 15.2
Expected Output: Average = 15.33
▼ Hint
- Add all three
doublevalues together first. - Divide the total by
3to get the average. - Use
Math.Round()if you want to limit the number of decimal places in the output.
▼ Solution & Explanation
Explanation:
(firstNumber + secondNumber + thirdNumber) / 3: Adds all three numbers and divides the total by the count to compute the average.Math.Round(average, 2): Rounds the result to two decimal places for a cleaner, more readable output.Console.WriteLine($"Average = {average}");: Prints the label together with the computed average.
Exercise 6: Remainder Finder
Practice Problem: Declare two integers and display the remainder of their division using the modulus (%) operator.
Purpose: This exercise helps you practice using the modulus operator, which is widely used for tasks like checking divisibility, cycling through values, and formatting numbers.
Given Input: firstNumber = 17, secondNumber = 5
Expected Output: Remainder = 2
▼ Hint
Use the % operator between the two integers to get the remainder left over after division.
▼ Solution & Explanation
Explanation:
int remainder = firstNumber % secondNumber;: The modulus operator%dividesfirstNumberbysecondNumberand returns what is left over instead of the quotient.Console.WriteLine($"Remainder = {remainder}");: Prints the label alongside the calculated remainder.
Exercise 7: Days to Years/Weeks
Practice Problem: Declare a number of days (e.g., 400) and convert it into years, weeks, and remaining days.
Purpose: This exercise helps you practice combining integer division and the modulus operator to break a single value down into meaningful units, a pattern common in time and unit conversions.
Given Input: totalDays = 400
Expected Output:
Years = 1 Weeks = 4 Remaining Days = 5
▼ Hint
- Use integer division (
/) by365to get the number of full years, then use%to get the days left over. - Take the leftover days and divide by
7to get full weeks, using%again for the final remaining days. - Work through the calculation step by step instead of trying to do it all in one line.
▼ Solution & Explanation
Explanation:
int years = totalDays / 365;: Uses integer division to find how many full years fit into the total days.int daysAfterYears = totalDays % 365;: Finds the days left over after removing full years.int weeks = daysAfterYears / 7;: Divides the leftover days by 7 to find the number of full weeks.int remainingDays = daysAfterYears % 7;: Finds the final leftover days that do not make up a full week.
Exercise 8: Even or Odd
Practice Problem: Check if a given integer is even or odd.
Purpose: This exercise helps you practice using the modulus operator together with a conditional statement to make a decision based on a number’s value.
Given Input: number = 7
Expected Output: 7 is Odd
▼ Hint
- Use
number % 2to check the remainder when dividing by 2. - If the remainder equals
0, the number is even; otherwise it is odd. - Use an
if...elsestatement to print the appropriate message.
▼ Solution & Explanation
Explanation:
number % 2 == 0: Checks whether dividing the number by 2 leaves no remainder, which means the number is even.if...else: Chooses which message to print based on the result of the condition.
Exercise 9: Swap Two Numbers
Practice Problem: Declare two integer variables and swap their values using a temporary variable.
Purpose: This exercise helps you practice a classic variable-swapping pattern, reinforcing how assignment and temporary storage work in memory.
Given Input: firstNumber = 5, secondNumber = 10
Expected Output:
Before Swap: firstNumber = 5, secondNumber = 10 After Swap: firstNumber = 10, secondNumber = 5
▼ Hint
- Store the value of
firstNumberin a temporary variable before overwriting it. - Assign the value of
secondNumbertofirstNumber. - Assign the temporary variable’s value to
secondNumberto complete the swap.
▼ Solution & Explanation
Explanation:
int temp = firstNumber;: Saves the original value offirstNumberin a temporary variable so it is not lost.firstNumber = secondNumber;: OverwritesfirstNumberwith the value ofsecondNumber.secondNumber = temp;: Assigns the original value offirstNumber, held intemp, tosecondNumber, completing the swap.
Exercise 10: Simple Interest Calculator
Practice Problem: Declare the principal amount, interest rate, and time period, then calculate and print the simple interest.
Purpose: This exercise helps you practice applying a real-world formula with multiple input variables, a common pattern in financial and business calculations.
Given Input: principal = 1000, rate = 5, time = 2
Expected Output: Simple Interest = 100
▼ Hint
- The formula for simple interest is
SI = (Principal * Rate * Time) / 100. - Declare each value (
principal,rate,time) as a separate variable. - Use
doubleif you expect decimal results.
▼ Solution & Explanation
Explanation:
double principal = 1000;: Declares the starting amount used in the calculation.(principal * rate * time) / 100: Applies the standard simple interest formula to compute the result.Console.WriteLine($"Simple Interest = {simpleInterest}");: Prints the label together with the calculated interest amount.
Exercise 11: Find the Maximum
Practice Problem: Declare three numbers and determine which one is the largest.
Purpose: This exercise helps you practice comparing multiple values using conditional logic, a skill used constantly in sorting, validation, and decision-making code.
Given Input: firstNumber = 12, secondNumber = 45, thirdNumber = 30
Expected Output: Maximum = 45
▼ Hint
- Compare
firstNumberandsecondNumberfirst usingMath.Max()to find the larger of the two. - Compare that result with
thirdNumberto find the overall largest value. - You could also write this using a series of
ifstatements instead ofMath.Max().
▼ Solution & Explanation
Explanation:
Math.Max(secondNumber, thirdNumber): Returns the larger ofsecondNumberandthirdNumber.Math.Max(firstNumber, ...): ComparesfirstNumberagainst the result of the inner comparison to find the overall largest value.Console.WriteLine($"Maximum = {max}");: Prints the label together with the largest value found.
Exercise 12: Leap Year Checker
Practice Problem: Write a program that checks whether a year is a leap year.
Purpose: This exercise helps you practice combining logical operators to express a multi-part rule, a pattern common in validation and date-related logic.
Given Input: year = 2024
Expected Output: 2024 is a Leap Year
▼ Hint
- A year is a leap year if it is divisible by 4.
- However, if it is also divisible by 100, it is not a leap year, unless it is divisible by 400 as well.
- Combine these checks using
%,&&, and||in a single condition.
▼ Solution & Explanation
Explanation:
year % 4 == 0 && year % 100 != 0: True when the year is divisible by 4 but not by 100.year % 400 == 0: Catches the special case where century years divisible by 400 are still leap years.||: Combines both conditions so the year is a leap year if either one is true.
Exercise 13: Uppercase Converter
Practice Problem: Convert a lowercase string to uppercase.
Purpose: This exercise helps you practice using a built-in string method to transform text, a common step in formatting and normalizing user input.
Given Input: text = "hello world"
Expected Output: HELLO WORLD
▼ Hint
C# strings have a built-in ToUpper() method that returns a new string with every letter converted to uppercase.
▼ Solution & Explanation
Explanation:
text.ToUpper(): Calls the built-inToUpper()method on the string, which returns a new string with all characters converted to uppercase.string upperText = ...: Stores the converted string in a new variable since strings in C# are immutable and cannot be changed in place.
Exercise 14: Count Characters
Practice Problem: Count how many characters a string contains.
Purpose: This exercise helps you practice using a string’s built-in Length property, useful whenever you need to validate or measure text input.
Given Input: text = "Programming"
Expected Output: Character Count = 11
▼ Hint
Every string in C# has a Length property that returns the total number of characters it contains.
▼ Solution & Explanation
Explanation:
text.Length: Accesses theLengthproperty of the string, which returns the total number of characters it holds.Console.WriteLine($"Character Count = {count}");: Prints the label together with the character count.
Exercise 15: Count to Ten
Practice Problem: Print numbers from 1 to 10 using a for loop.
Purpose: This exercise helps you practice the structure of a for loop, including initialization, condition, and increment, the foundation for repeating tasks in code.
Given Input: None
Expected Output:
1 2 3 4 5 6 7 8 9 10
▼ Hint
- A
forloop has three parts: a starting value, a condition, and an update step. - Start the counter at
1and continue while it is less than or equal to10. - Increase the counter by
1after each iteration usingi++.
▼ Solution & Explanation
Explanation:
int i = 1: Initializes the loop counter at 1.i <= 10: The loop continues running as long as this condition is true.i++: Increases the counter by 1 after each loop iteration.
Exercise 16: Countdown
Practice Problem: Print numbers from 10 down to 1 using a while loop.
Purpose: This exercise helps you practice writing a while loop that decreases a counter, reinforcing how loop conditions and updates control repetition.
Given Input: None
Expected Output:
10 9 8 7 6 5 4 3 2 1
▼ Hint
- Start a counter variable at
10before the loop begins. - Use a
whileloop that continues as long as the counter is greater than0. - Decrease the counter by 1 inside the loop body using
i--.
▼ Solution & Explanation
Explanation:
int i = 10;: Initializes the counter before the loop starts.while (i >= 1): Keeps the loop running as long as the counter has not dropped below 1.i--;: Decreases the counter by 1 on each pass, eventually causing the loop to stop.
Exercise 17: Multiplication Table
Practice Problem: Display the multiplication table (up to 10) for a given number.
Purpose: This exercise helps you practice using a loop counter inside a calculation, a pattern used whenever you need to generate a repeated series of results.
Given Input: number = 5
Expected Output:
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
▼ Hint
- Use a
forloop with the counter running from1to10. - Inside the loop, multiply
numberby the current counter value. - Use string interpolation to format each line consistently.
▼ Solution & Explanation
Explanation:
for (int i = 1; i <= 10; i++): Loops the counterifrom 1 through 10.number * i: Multiplies the fixed number by the current loop counter to produce each line of the table.$"{number} x {i} = {number * i}": Uses string interpolation to format the multiplication expression and its result on one line.
Exercise 18: Sum of N Numbers
Practice Problem: Calculate the sum of all integers from 1 to N.
Purpose: This exercise helps you practice using a loop to accumulate a running total, a foundational pattern used in many summation and aggregation tasks.
Given Input: n = 10
Expected Output: Sum = 55
▼ Hint
- Initialize a variable
sum = 0before the loop. - Use a
forloop from1ton, adding each value tosum. - Print
sumafter the loop finishes.
▼ Solution & Explanation
Explanation:
int sum = 0;: Initializes the accumulator to zero before the loop starts.sum += i;: Adds the current loop value tosumon every iteration.Console.WriteLine($"Sum = {sum}");: Prints the final total once the loop has finished running.
Exercise 19: Factorial Calculator
Practice Problem: Compute the factorial of a positive integer (e.g., 5! = 5*4*3*2*1).
Purpose: This exercise helps you practice using a loop to repeatedly multiply values together, a pattern that also builds intuition for recursion later on.
Given Input: n = 5
Expected Output: Factorial = 120
▼ Hint
- Initialize a variable
factorial = 1, not0, since you will be multiplying. - Use a
forloop from1ton, multiplyingfactorialby each value. - Use a
longinstead ofintif you expect larger values ofn.
▼ Solution & Explanation
Explanation:
long factorial = 1;: Starts the accumulator at 1 since multiplying by 0 would always result in 0.factorial *= i;: Multiplies the running total by the current loop value on each iteration.long: Used instead ofintbecause factorial results grow very quickly and can exceed the range ofint.
Exercise 20: Even Numbers Only
Practice Problem: Write a loop that prints all even numbers between 1 and 50.
Purpose: This exercise helps you practice combining a loop with a conditional check to filter values, a common pattern when processing only the items that meet a certain rule.
Given Input: None
Expected Output:
2 4 6 ... 48 50
▼ Hint
- Loop through every number from
1to50. - Inside the loop, use
% 2 == 0to check whether the current number is even. - Only print the number if the condition is true. As a shortcut, you could also start the loop at
2and increase by2each time.
▼ Solution & Explanation
Explanation:
for (int i = 1; i <= 50; i++): Loops through every number from 1 to 50.i % 2 == 0: Checks whether the current number divides evenly by 2, which means it is even.Console.WriteLine(i);: Prints the number only when it passes the even check inside theifstatement.
Exercise 21: Array Initialization
Practice Problem: Create an array of 5 integers, assign them values, and print each element using a foreach loop.
Purpose: This exercise helps you practice declaring and initializing an array, then iterating over it with foreach, a pattern used constantly when working with collections of data.
Given Input: numbers = [10, 20, 30, 40, 50]
Expected Output:
10 20 30 40 50
▼ Hint
- Declare the array with
int[] numbers = new int[5] { ... };and provide the five values. - Use a
foreachloop to iterate through the array without needing an index. - Print each value inside the loop body using
Console.WriteLine().
▼ Solution & Explanation
Explanation:
int[] numbers = new int[5] { ... };: Declares an array that can hold 5 integers and initializes it with the given values.foreach (int number in numbers): Iterates through every element in the array, assigning each value tonumberin turn.Console.WriteLine(number);: Prints the current element on its own line.
Exercise 22: Find Min/Max in Array
Practice Problem: Loop through an array of numbers to find and print both the smallest and largest values.
Purpose: This exercise helps you practice tracking running values as you iterate through a collection, a pattern used in statistics, filtering, and ranking tasks.
Given Input: numbers = [12, 45, 3, 67, 21]
Expected Output:
Minimum = 3 Maximum = 67
▼ Hint
- Start by assuming the first element is both the minimum and the maximum.
- As you loop through the rest of the array, update
minwhenever you find a smaller value. - Update
maxwhenever you find a larger value.
▼ Solution & Explanation
Explanation:
int min = numbers[0]; int max = numbers[0];: Initializes both trackers using the first element as a starting point.if (number < min): Updatesminwhenever a smaller value is found while looping.if (number > max): Updatesmaxwhenever a larger value is found while looping.
Exercise 23: Array Reverser
Practice Problem: Take an array of strings and print them in reverse order.
Purpose: This exercise helps you practice using array indexes and length to control the direction of iteration, useful whenever data needs to be processed back to front.
Given Input: fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
Expected Output:
Elderberry Date Cherry Banana Apple
▼ Hint
- Use
fruits.Lengthto find the total number of elements. - Start a
forloop at the last valid index (Length - 1) and count down to0. - Print each element using its index inside the loop.
▼ Solution & Explanation
Explanation:
fruits.Length - 1: Finds the index of the last element, since array indexes start at 0.for (int i = fruits.Length - 1; i >= 0; i--): Loops backwards from the last index down to the first.fruits[i]: Accesses the element at the current index, printing the array in reverse order.
Exercise 24: Sum of Array Elements
Practice Problem: Write a program to sum all the elements inside a double array.
Purpose: This exercise helps you practice accumulating values from an array using a loop, reinforcing the same running-total pattern applied to floating-point data.
Given Input: numbers = [10.5, 20.3, 5.2, 8.0]
Expected Output: Sum = 44
▼ Hint
- Initialize a
double sum = 0;before the loop. - Use a
foreachloop to add each array element tosum. - Print
sumonce the loop finishes.
▼ Solution & Explanation
Explanation:
double sum = 0;: Initializes the accumulator to zero before the loop starts.foreach (double number in numbers): Iterates through every value in the array.sum += number;: Adds the current array element to the running total on each pass.
Exercise 25: Search an Element
Practice Problem: Ask the user for a number and check if it exists inside a predefined array, returning its index position.
Purpose: This exercise helps you practice reading user input, converting it to a number, and performing a linear search, a foundational algorithm used throughout programming.
Given Input: numbers = [4, 8, 15, 16, 23, 42], user enters 16
Expected Output: 16 found at index 3
▼ Hint
- Read the user’s input with
Console.ReadLine()and convert it to anintusingint.Parse(). - Loop through the array with a regular
forloop so you have access to the index. - When a match is found, store the index and stop searching with
break.
▼ Solution & Explanation
Explanation:
int.Parse(Console.ReadLine()): Reads the text typed by the user and converts it into an integer for comparison.int index = -1;: Starts with a sentinel value that indicates the number has not been found yet.if (numbers[i] == target): Compares each array element with the target value, and if it matches, records the index and exits the loop withbreak.
Exercise 26: Dynamic Integer List
Practice Problem: Create a List<int>, add numbers to it dynamically in a loop, and print the final count of items.
Purpose: This exercise helps you practice using List<T>, a resizable collection that grows automatically, unlike a fixed-size array.
Given Input: Add 5 numbers in a loop (10, 20, 30, 40, 50)
Expected Output: Total Items = 5
▼ Hint
- Add
using System.Collections.Generic;at the top so you can useList<T>. - Create an empty list with
new List<int>(). - Use a loop to call
Add()multiple times, then printCount.
▼ Solution & Explanation
Explanation:
List<int> numbers = new List<int>();: Creates an empty, resizable list that can hold integers.numbers.Add(i * 10);: Adds a new value to the list on each loop iteration, growing the list dynamically.numbers.Count: Returns the total number of items currently stored in the list.
Exercise 27: Remove Duplicates
Practice Problem: Take a list of numbers with duplicate values and filter them so only unique numbers remain.
Purpose: This exercise helps you practice checking whether a collection already contains a value before adding it, a common step in data cleaning and deduplication.
Given Input: numbers = [1, 2, 2, 3, 4, 4, 5]
Expected Output: Unique Numbers: 1, 2, 3, 4, 5
▼ Hint
- Create a second, empty list to hold only the unique values.
- Loop through the original list, and before adding a number, check with
Contains()whether it is already in the new list. - Use
string.Join()to print the final list as a single comma-separated line.
▼ Solution & Explanation
Explanation:
!uniqueNumbers.Contains(number): Checks whether the value is not already present in the new list before adding it.uniqueNumbers.Add(number);: Adds the number to the unique list only when it passes the duplicate check.string.Join(", ", uniqueNumbers): Combines all the unique values into a single, comma-separated string for display.
Exercise 28: String Reverser
Practice Problem: Create a function that accepts a string as an argument and returns the string completely reversed.
Purpose: This exercise helps you practice writing a reusable method with a parameter and a return value, a core skill for organizing code into smaller, testable pieces.
Given Input: text = "Hello"
Expected Output: olleH
▼ Hint
- Convert the string to a character array using
ToCharArray(). - Use
Array.Reverse()to reverse the character array in place. - Build a new string from the reversed array using
new string(characters)and return it.
▼ Solution & Explanation
Explanation:
static string ReverseString(string input): Defines a reusable method that takes a string parameter and returns a string result.input.ToCharArray(): Converts the string into an array of individual characters so they can be rearranged.Array.Reverse(characters): Reverses the order of elements in the character array in place.new string(characters): Builds a new string from the reversed character array, which is then returned to the caller.
Exercise 29: Is Prime Function
Practice Problem: Write a boolean method IsPrime(int number) that returns true if a number is prime and false otherwise.
Purpose: This exercise helps you practice writing a method that returns a boolean result, along with looping and early exits, a common structure for validation logic.
Given Input: number = 17
Expected Output: 17 is Prime: True
▼ Hint
- Numbers less than 2 are never prime, so return
falseimmediately for those. - Loop from
2up to the square root of the number, checking for divisors with%. - If any divisor is found, return
false; if the loop completes without finding one, returntrue.
▼ Solution & Explanation
Explanation:
if (number < 2) return false;: Handles the edge case where numbers below 2 are never prime.for (int i = 2; i <= Math.Sqrt(number); i++): Checks for divisors only up to the square root of the number, which is enough to confirm primality.if (number % i == 0) return false;: If a divisor is found, the number is not prime, so the method exits early.return true;: If no divisors were found after the loop, the number is confirmed to be prime.
Exercise 30: Create a Car Class
Practice Problem: Design a Car class with properties like Make, Model, and Year. Instantiate an object of this class and print its details.
Purpose: This exercise helps you practice defining a class with properties and creating an object from it, the foundation of object-oriented programming in C#.
Given Input: Make = "Toyota", Model = "Corolla", Year = 2022
Expected Output:
Make: Toyota Model: Corolla Year: 2022
▼ Hint
- Define a
Carclass with three public properties using auto-implemented property syntax, e.g.public string Make { get; set; }. - In
Main, create a newCarobject and assign values to each property. - Print each property using string interpolation.
▼ Solution & Explanation
Explanation:
public string Make { get; set; }: Defines an auto-implemented property that can be read and written from outside the class.Car myCar = new Car();: Creates a new instance of theCarclass, called an object.myCar.Make = "Toyota";: Sets the object’sMakeproperty using dot notation.class Program: A separate class holdingMain, kept apart from theCarclass to reflect standard object-oriented organization.
Exercise 31: Class Methods
Practice Problem: Add a Drive() method to your Car class that prints out “The [Make] [Model] is driving!”
Purpose: This exercise helps you practice adding behavior to a class through instance methods, which can read the object’s own properties without needing them passed in as parameters.
Given Input: Make = "Toyota", Model = "Corolla"
Expected Output: The Toyota Corolla is driving!
▼ Hint
- Define a method named
Drive()inside theCarclass with avoidreturn type. - Inside the method, use
MakeandModeldirectly since they belong to the same object. - Call
myCar.Drive()fromMainafter setting the properties.
▼ Solution & Explanation
Explanation:
public void Drive(): Defines an instance method that belongs to everyCarobject and returns no value.$"The {Make} {Model} is driving!": Reads the object’s ownMakeandModelproperties directly, without needing them passed in as arguments.myCar.Drive();: Calls the method on the specificmyCarobject using dot notation.
Exercise 32: Constructors
Practice Problem: Implement a custom constructor for a Book class that forces the user to set the Title and Author upon creation.
Purpose: This exercise helps you practice writing a custom constructor, which guarantees an object cannot be created without the required data it needs to be valid.
Given Input: Title = "1984", Author = "George Orwell"
Expected Output:
Title: 1984 Author: George Orwell
▼ Hint
- Define a constructor with the same name as the class, taking
titleandauthoras parameters. - Inside the constructor, assign the parameters to the class properties.
- Since there is no parameterless constructor, you must pass both values when creating the object, e.g.
new Book("1984", "George Orwell").
▼ Solution & Explanation
Explanation:
public Book(string title, string author): Defines a constructor that runs automatically when a newBookis created, requiring both parameters.Title = title; Author = author;: Assigns the incoming constructor parameters to the object’s properties.new Book("1984", "George Orwell"): Creates aBookobject by supplying both required values, since no parameterless constructor exists.
Exercise 33: Bank Account Encapsulation
Practice Problem: Create a BankAccount class with a private field balance. Provide public methods for Deposit() and Withdraw() to manipulate the balance safely.
Purpose: This exercise helps you practice encapsulation, keeping internal state private and only allowing it to change through controlled public methods.
Given Input: Deposit 500, then withdraw 200
Expected Output: Balance = 300
▼ Hint
- Declare
balanceasprivateso it cannot be changed directly from outside the class. - In
Deposit(), add the given amount tobalance. - In
Withdraw(), check thatbalanceis sufficient before subtracting the amount, and provide a public method or property to read the current balance.
▼ Solution & Explanation
Explanation:
private double balance;: Hides the field from outside code, so it can only be changed through the class’s own methods.public void Deposit(double amount): A controlled entry point that safely increases the balance.if (amount <= balance): Prevents withdrawing more money than is available in the account.public double GetBalance(): Provides safe, read-only access to the private balance from outside the class.
Exercise 34: Basic Inheritance
Practice Problem: Create a base class named Animal with a method MakeSound(). Create a derived class Dog that overrides MakeSound() to print “Bark!”.
Purpose: This exercise helps you practice inheritance and method overriding, letting a derived class provide its own specific behavior for a method defined in its base class.
Given Input: None
Expected Output: Bark!
▼ Hint
- Mark the base class method as
virtualso it can be overridden. - In the
Dogclass, use: Animalto inherit from it, and mark the overriding method withoverride. - Assign a
Dogobject to anAnimalvariable to see the overridden method run.
▼ Solution & Explanation
Explanation:
public virtual void MakeSound(): Marks the base class method as overridable by any derived class.class Dog : Animal: Declares thatDoginherits all members fromAnimal.public override void MakeSound(): Replaces the base class behavior with theDog-specific implementation.Animal myDog = new Dog();: Even though the variable type isAnimal, callingMakeSound()runs the overridden version fromDog.
Exercise 35: The Point Struct
Practice Problem: Create a struct called Point with X and Y coordinates. Write a method inside it to calculate the distance from the origin (0,0).
Purpose: This exercise helps you practice defining a lightweight struct to group related values together, along with adding a method that operates on the struct’s own fields.
Given Input: X = 3, Y = 4
Expected Output: Distance = 5
▼ Hint
- Declare
XandYas public fields or properties inside thestruct. - The distance from the origin follows the Pythagorean formula:
sqrt(X^2 + Y^2). - Use
Math.Sqrt()together withMath.Pow(), or simply multiply each value by itself.
▼ Solution & Explanation
Explanation:
struct Point: Defines a value type that groups theXandYcoordinates together.Math.Sqrt(X * X + Y * Y): Applies the Pythagorean formula to calculate the straight-line distance from the origin.new Point { X = 3, Y = 4 }: Creates aPointinstance using object initializer syntax to set both fields at once.
Exercise 36: Immutable Color Struct
Practice Problem: Design a struct representing a Color (RGB values). Make it completely immutable by using readonly properties and a constructor.
Purpose: This exercise helps you practice building immutable types, where values are set once at creation and can never be changed afterward, reducing bugs from unexpected state changes.
Given Input: R = 255, G = 0, B = 0
Expected Output:
R: 255 G: 0 B: 0
▼ Hint
- Use
{ get; }instead of{ get; set; }so the properties can only be assigned inside the constructor. - Write a constructor that takes
r,g, andband assigns them to the properties. - Marking the whole struct as
readonlyreinforces that none of its members can change after construction.
▼ Solution & Explanation
Explanation:
readonly struct Color: Declares the entire struct as immutable, meaning its fields cannot change once the object is created.public int R { get; }: A get-only property that can only be assigned inside the constructor, never afterward.public Color(int r, int g, int b): The only place whereR,G, andBcan be set, guaranteeing the object is fully valid the moment it is created.
Exercise 37: Product Record
Practice Problem: Create a simple record Product(string Name, decimal Price). Instantiate two identical products and show that Console.WriteLine(prod1 == prod2) returns true (demonstrating value-based equality).
Purpose: This exercise helps you practice using C#’s record type, which compares objects by their values instead of by reference, unlike a regular class.
Given Input: prod1 = ("Book", 15.99), prod2 = ("Book", 15.99)
Expected Output: True
▼ Hint
- Declare the record using the concise positional syntax:
record Product(string Name, decimal Price);. - Create two separate
Productinstances with the same values. - Compare them with
==. Unlike a class, records compare their contents rather than their memory reference.
▼ Solution & Explanation
Explanation:
record Product(string Name, decimal Price);: Declares an immutable record type using positional syntax, which automatically generates properties and value-based equality.prod1 == prod2: Compares the two records by their property values rather than by memory reference, so two separately created records with identical data are considered equal.
Exercise 38: Updating Records (with Expression)
Practice Problem: Create a record Student with Name and Grade. Use the with expression to create a copy of a student object but with an updated Grade.
Purpose: This exercise helps you practice non-destructive mutation with the with expression, which produces a new record instance instead of changing the original.
Given Input: student1 = ("Alice", "B"), updated Grade = "A"
Expected Output:
Name: Alice, Grade: B Name: Alice, Grade: A
▼ Hint
- Declare the record as
record Student(string Name, string Grade);. - Use
student1 with { Grade = "A" }to produce a new record with only theGradechanged. - Print both records to confirm the original was not modified.
▼ Solution & Explanation
Explanation:
student1 with { Grade = "A" }: Creates a brand newStudentrecord that copies all values fromstudent1, exceptGrade, which is replaced with the new value.student1.Grade: Remains"B"after thewithexpression, proving the original record was never changed.
Exercise 39: Dynamic Grocery List (List<T>)
Practice Problem: Write a program that allows a user to dynamically add, remove, and view items in a List<string>.
Purpose: This exercise helps you practice building a simple interactive menu driven by user input, combined with the core List<T> operations of adding, removing, and displaying items.
Given Input: User enters 1 (add) with “Milk”, 1 (add) with “Bread”, 2 (remove) with “Milk”, 3 (view), then 4 (exit)
Expected Output:
Grocery List: - Bread
▼ Hint
- Use a
whileloop to keep showing the menu until the user chooses to exit. - Read the menu choice with
Console.ReadLine()and use aswitchstatement to handle each option. - Use
Add()andRemove()on the list, and aforeachloop to print all items when viewing the list.
▼ Solution & Explanation
Explanation:
while (running): Keeps showing the menu and processing choices until the user selects the exit option.switch (choice): Routes execution to the correct block of code based on the user’s menu selection.groceryList.Add(itemToAdd);: Appends a new item to the end of the list.groceryList.Remove(itemToRemove);: Removes the first matching item found in the list.running = false;: Ends thewhileloop, closing the program cleanly.
Exercise 40: Contact Directory (Dictionary<TKey, TValue>)
Practice Problem: Create a phonebook directory using a dictionary where the key is a person’s name and the value is their phone number. Allow the user to search for a number by name.
Purpose: This exercise helps you practice using Dictionary<TKey, TValue> for fast key-based lookups, along with safely checking whether a key exists before retrieving its value.
Given Input: Directory contains Alice: 555-1234 and Bob: 555-5678. User searches for Alice.
Expected Output: Alice's number: 555-1234
▼ Hint
- Create the dictionary with
new Dictionary<string, string>()and add entries using either the initializer syntax orAdd(). - Read the search name with
Console.ReadLine(). - Use
TryGetValue()to safely look up the name without risking an error if it is not found.
▼ Solution & Explanation
Explanation:
Dictionary<string, string> contacts = ...: Creates a collection of key-value pairs, mapping each name to a phone number.{ "Alice", "555-1234" }: Uses collection initializer syntax to add an entry directly when the dictionary is created.contacts.TryGetValue(searchName, out string number): Safely attempts to retrieve the value for the given key, returningtrueorfalseinstead of throwing an error if the name is missing.
Exercise 41: Unique Registration (HashSet<T>)
Practice Problem: Build a system that accepts student IDs. Use a HashSet<int> to ensure that no duplicate IDs can be registered.
Purpose: This exercise helps you practice using HashSet<T>, a collection that automatically enforces uniqueness, useful whenever duplicate entries must be rejected.
Given Input: idsToRegister = [101, 102, 101, 103]
Expected Output:
101 registered successfully. 102 registered successfully. 101 is already registered. 103 registered successfully.
▼ Hint
- Add
using System.Collections.Generic;to useHashSet<T>. - The
Add()method on aHashSetreturnstrueif the item was added andfalseif it was already present. - Use that return value inside an
ifstatement to print the correct message for each ID.
▼ Solution & Explanation
Explanation:
HashSet<int> studentIds = new HashSet<int>();: Creates a collection that automatically rejects duplicate values.studentIds.Add(id): Attempts to add the ID, returningtrueif it was new andfalseif it already existed in the set.if (studentIds.Add(id)): Uses the boolean return value directly in the condition to decide which message to print.
Exercise 42: Undo Mechanism (Stack<T>)
Practice Problem: Simulate a text editor’s “Undo” feature using a Stack<string>. Every time a user types a word, push it to the stack. Pop the last word when they type “undo”.
Purpose: This exercise helps you practice using a Stack<T>, a last-in-first-out collection well suited to undo history, call tracking, and reversing recent actions.
Given Input: actions = ["Hello", "World", "undo"]
Expected Output:
Typed: Hello Typed: World Undo: removed "World" Remaining words: Hello
▼ Hint
- Use
Push()to add a typed word to the top of the stack. - When the action is “undo”, use
Pop()to remove and return the most recently typed word. - Check
Count > 0before popping, so you don’t try to undo when the stack is empty.
▼ Solution & Explanation
Explanation:
history.Push(action);: Adds the typed word to the top of the stack.history.Pop();: Removes and returns the most recently pushed word, simulating an undo of the last action.if (history.Count > 0): Guards against callingPop()on an empty stack, which would otherwise throw an error.
Exercise 43: Customer Service Line (Queue<T>)
Practice Problem: Simulate a bank line using a Queue<string>. Enqueue 3 customers, then dequeue them one by one, printing who is being served.
Purpose: This exercise helps you practice using a Queue<T>, a first-in-first-out collection ideal for modeling waiting lines, task processing, and ordered workflows.
Given Input: customers = ["Alice", "Bob", "Charlie"]
Expected Output:
Serving: Alice Serving: Bob Serving: Charlie
▼ Hint
- Use
Enqueue()to add each customer to the back of the line. - Use a
whileloop that continues as long asCount > 0. - Use
Dequeue()inside the loop to remove and serve the customer at the front of the line.
▼ Solution & Explanation
Explanation:
customers.Enqueue("Alice");: Adds a customer to the back of the queue.while (customers.Count > 0): Keeps serving customers until the queue is empty.customers.Dequeue();: Removes and returns the customer at the front of the queue, preserving first-in-first-out order.
Exercise 44: Sorted Inventory (SortedList<TKey, TValue>)
Practice Problem: Store products with their item codes as keys. Use a SortedList so that the inventory automatically displays items sorted by their code.
Purpose: This exercise helps you practice using SortedList<TKey, TValue>, which keeps its entries ordered by key automatically, removing the need for a separate sorting step.
Given Input: Added in this order: B002 = Gadget, A001 = Widget, C003 = Gizmo
Expected Output:
A001: Widget B002: Gadget C003: Gizmo
▼ Hint
- Create a
SortedList<string, string>and add entries in any order usingAdd(). - Unlike a regular
Dictionary, aSortedListautomatically keeps its keys in sorted order internally. - Loop through it with
foreachusing aKeyValuePairto print each entry.
▼ Solution & Explanation
Explanation:
SortedList<string, string> inventory = ...: Creates a collection that automatically maintains its entries sorted by key.inventory.Add("B002", "Gadget");: Adds an entry regardless of insertion order, since the sorted position is handled internally.foreach (KeyValuePair<string, string> item in inventory): Iterates through the entries in sorted key order, printing each item code alongside its product name.
Exercise 45: Key-Value Iteration
Practice Problem: Create a Dictionary<string, double> of products and prices. Write a foreach loop that cleanly prints out: “Product: [Key] costs $[Value]”.
Purpose: This exercise helps you practice iterating over a dictionary’s key-value pairs together, a common pattern when displaying or reporting on stored data.
Given Input: Laptop = 999.99, Mouse = 25.50, Keyboard = 45.00
Expected Output:
Product: Laptop costs $999.99 Product: Mouse costs $25.5 Product: Keyboard costs $45
▼ Hint
- Use collection initializer syntax to populate the dictionary directly when it is declared.
- Loop through the dictionary with
foreach (KeyValuePair<string, double> product in products). - Access
product.Keyandproduct.Valueinside a string interpolation to build the message.
▼ Solution & Explanation
Explanation:
{ "Laptop", 999.99 }: Adds a key-value pair to the dictionary at the moment it is created.foreach (KeyValuePair<string, double> product in products): Iterates over each entry, giving access to both the key and the value together.product.Key/product.Value: Reads the product name and its price from the current key-value pair.
Exercise 46: Collection Clearing & Checking
Practice Problem: Write a program that populates a list, checks if a specific element exists using .Contains(), and then clears the entire list using .Clear().
Purpose: This exercise helps you practice two common list maintenance operations: checking for membership and emptying a collection entirely.
Given Input: items = ["Pen", "Notebook", "Eraser"]
Expected Output:
Contains Notebook: True Item Count After Clear: 0
▼ Hint
- Use
Contains()to check whether a value is present in the list, which returns abool. - Use
Clear()to remove every element from the list at once. - Print
Countafter clearing to confirm the list is now empty.
▼ Solution & Explanation
Explanation:
items.Contains("Notebook"): Checks whether the value exists anywhere in the list and returnstrueorfalse.items.Clear();: Removes all elements from the list, leaving it empty but still usable.items.Count: Confirms the list is empty by returning0after the clear operation.
Exercise 47: Filtering Even Numbers
Practice Problem: Given a list of integers from 1 to 20, use a LINQ lambda expression (.Where()) to filter out and display only the even numbers.
Purpose: This exercise helps you practice using LINQ’s .Where() method with a lambda expression, a concise alternative to writing a manual filtering loop.
Given Input: numbers = 1 to 20
Expected Output:
2 4 6 ... 18 20
▼ Hint
- Add
using System.Linq;to enable LINQ methods. - Use
Enumerable.Range(1, 20)to generate the numbers 1 through 20. - Call
.Where(n => n % 2 == 0)to keep only the values that pass the even check.
▼ Solution & Explanation
Explanation:
Enumerable.Range(1, 20).ToList(): Generates a list containing the integers from 1 to 20.numbers.Where(n => n % 2 == 0): Filters the list, keeping only the numbers where the lambda expression evaluates totrue.var evenNumbers = ...: Stores the filtered sequence, which is then iterated with aforeachloop to print each value.
Exercise 48: Top Scorers
Practice Problem: Given a list of student exam scores, use LINQ to filter scores greater than 80 and sort them in descending order using .OrderByDescending().
Purpose: This exercise helps you practice chaining multiple LINQ methods together, filtering first and then sorting the result in a single, readable expression.
Given Input: scores = [75, 88, 92, 60, 85]
Expected Output:
92 88 85
▼ Hint
- Use
.Where(s => s > 80)first to keep only scores above 80. - Chain
.OrderByDescending(s => s)directly after.Where()to sort the filtered results. - LINQ methods can be chained one after another since each one returns a new sequence.
▼ Solution & Explanation
Explanation:
scores.Where(s => s > 80): Filters the list down to only the scores above 80..OrderByDescending(s => s): Sorts the filtered scores from highest to lowest.var topScores = ...: Stores the combined result of filtering and sorting, ready to be looped over and printed.
Exercise 49: String Transformation (.Select())
Practice Problem: Take a list of city names (e.g., “london”, “paris”) and use LINQ’s .Select() method to transform them into all uppercase letters.
Purpose: This exercise helps you practice using LINQ’s .Select() method to project each element of a sequence into a new, transformed value.
Given Input: cities = ["london", "paris", "tokyo"]
Expected Output:
LONDON PARIS TOKYO
▼ Hint
- Use
.Select(c => c.ToUpper())to transform every element in the list. - Unlike
.Where(), which filters,.Select()changes each element into something new without removing any. - Loop through the transformed sequence with
foreachto print each uppercase city name.
▼ Solution & Explanation
Explanation:
cities.Select(c => c.ToUpper()): Projects every city name in the list through the lambda expression, producing a new sequence of uppercase strings.var upperCities = ...: Stores the transformed sequence without modifying the originalcitieslist.
Exercise 50: Aggregation (Min, Max, Average)
Practice Problem: Create a list of item prices. Use LINQ aggregation methods (.Sum(), .Average(), .Min(), and .Max()) to print out quick statistics on the data.
Purpose: This exercise helps you practice using LINQ’s built-in aggregation methods, which replace manual loops for common calculations like totals, averages, and extremes.
Given Input: prices = [19.99, 5.49, 42.00, 12.75]
Expected Output:
Sum = 80.23 Average = 20.0575 Min = 5.49 Max = 42
▼ Hint
- Each aggregation method can be called directly on the list, e.g.
prices.Sum(). - No lambda expression is needed for these methods since they operate on the whole sequence at once.
- Print each result with a descriptive label using string interpolation.
▼ Solution & Explanation
Explanation:
prices.Sum(): Adds together every value in the list.prices.Average(): Divides the sum by the number of elements to compute the mean.prices.Min()/prices.Max(): Scan the list to return the smallest and largest values respectively.
Exercise 51: Find the First Match
Practice Problem: Create a list of names. Use .FirstOrDefault() to find the first name that starts with the letter ‘J’. Handle the case where no such name exists.
Purpose: This exercise helps you practice using LINQ’s .FirstOrDefault() method, which safely returns a matching element or a default value instead of throwing an error when nothing matches.
Given Input: names = ["Michael", "Sarah", "James", "Laura"]
Expected Output: First match: James
▼ Hint
- Add
using System.Linq;to enable.FirstOrDefault(). - Pass a lambda expression like
n => n.StartsWith("J")to define the matching condition. - If no element matches,
.FirstOrDefault()returnsnullfor a string list, so check for that before printing.
▼ Solution & Explanation
Explanation:
names.FirstOrDefault(n => n.StartsWith("J")): Scans the list and returns the first name that starts with “J”, ornullif none is found.if (firstMatch != null): Checks whether a match was actually found before using the result, avoiding a null-related error.
Exercise 52: Digital Clock/Current Time
Practice Problem: Print the current date and time in a specific format, such as MM/dd/yyyy HH:mm:ss.
Purpose: This exercise helps you practice formatting a DateTime value into a specific, readable string using custom format specifiers.
Given Input: None (uses the current system date and time)
Expected Output: 07/11/2026 14:32:10 (the exact value will differ depending on when you run the program)
▼ Hint
- Use
DateTime.Nowto get the current date and time. - Call
.ToString()on it with a custom format string like"MM/dd/yyyy HH:mm:ss". HHrepresents a 24-hour clock, whilehhwould represent a 12-hour clock.
▼ Solution & Explanation
Explanation:
DateTime.Now: Retrieves the current date and time from the system clock.now.ToString("MM/dd/yyyy HH:mm:ss"): Converts theDateTimevalue into a string using a custom format: two-digit month, day, four-digit year, followed by hours, minutes, and seconds.
Exercise 53: Age Calculator
Practice Problem: From a birthdate, use DateTime.Parse() and calculate exactly how many days old they are by subtracting it from DateTime.Today.
Purpose: This exercise helps you practice parsing a date from text and subtracting two DateTime values to get a TimeSpan, a common pattern in age and duration calculations.
Given Input: birthDateText = "1995-06-15"
Expected Output: You are 11349 days old. (the exact number depends on the current date when you run the program)
▼ Hint
- Use
DateTime.Parse()to convert the birthdate string into aDateTimevalue. - Subtracting one
DateTimefrom another produces aTimeSpan. - Use the
TimeSpan‘s.Daysproperty to get the whole number of days between the two dates.
▼ Solution & Explanation
Explanation:
DateTime.Parse(birthDateText): Converts the text representation of the birthdate into a properDateTimevalue.DateTime.Today - birthDate: Subtracts the two dates, producing aTimeSpanthat represents the difference between them.age.Days: Reads the total number of whole days contained in theTimeSpan.
Exercise 54: Adding/Subtracting Time
Practice Problem: Write a program that calculates what the exact date will be 45 days from today, and what day of the week it will land on.
Purpose: This exercise helps you practice using DateTime arithmetic methods like .AddDays(), along with reading the DayOfWeek property from the result.
Given Input: DateTime.Today
Expected Output: 45 days from today is 08/25/2026, which falls on a Tuesday. (the exact date and day depend on when you run the program)
▼ Hint
- Use
DateTime.Today.AddDays(45)to calculate the future date. - The resulting
DateTimehas aDayOfWeekproperty that returns the day name automatically. - Format the date using
.ToString("MM/dd/yyyy")for a clean display.
▼ Solution & Explanation
Explanation:
DateTime.Today.AddDays(45): Adds 45 days to today’s date, automatically handling month and year rollovers.{futureDate:MM/dd/yyyy}: Uses inline format syntax within string interpolation to display the date in a clean, fixed format.futureDate.DayOfWeek: Reads the day-of-week name directly from the calculatedDateTimevalue.
Exercise 55: Days in a Month
Practice Problem: Prompt the user for a year and a month number. Use the DateTime.DaysInMonth() method to output how many days are in that specific month (handling leap years automatically).
Purpose: This exercise helps you practice using a built-in calendar utility method instead of writing manual leap year logic yourself.
Given Input: year = 2024, month = 2
Expected Output: February 2024 has 29 days.
▼ Hint
- Read the year and month using
Console.ReadLine()and convert each to anintwithint.Parse(). - Call
DateTime.DaysInMonth(year, month), which returns the correct day count including leap year adjustments for February. - To display the month’s name, construct a temporary date, e.g.
new DateTime(year, month, 1).ToString("MMMM").
▼ Solution & Explanation
Explanation:
DateTime.DaysInMonth(year, month): Returns the correct number of days for the given month and year, automatically accounting for leap years in February.new DateTime(year, month, 1).ToString("MMMM"): Builds a temporary date on the first of the given month, then formats it to display the full month name.
Exercise 56: Diary Entry (Write Text)
Practice Problem: Prompt the user to type a sentence, then write that sentence into a file named diary.txt using File.WriteAllText().
Purpose: This exercise helps you practice basic file writing, a fundamental building block for any program that needs to save data outside the console.
Given Input: "Today was a great day!"
Expected Output: Your diary entry has been saved.
▼ Hint
- Add
using System.IO;to access file operations. - Read the sentence with
Console.ReadLine(). - Call
File.WriteAllText("diary.txt", sentence), which creates the file if it doesn’t exist and overwrites it if it does.
▼ Solution & Explanation
Explanation:
using System.IO;: Imports the namespace that contains theFileclass and its file handling methods.File.WriteAllText("diary.txt", entry): Writes the entered text todiary.txt, creating the file if needed and replacing its contents if it already exists.
Exercise 57: Log Append
Practice Problem: Create a program that appends timestamps to a file called log.txt every time it runs, using File.AppendAllText().
Purpose: This exercise helps you practice appending to a file rather than overwriting it, useful for building logs, histories, and other continuously growing records.
Given Input: None (uses the current system date and time each time the program runs)
Expected Output: Log entry added at 07/11/2026 14:32:10 (the exact value will differ depending on when you run the program)
▼ Hint
- Build the log line using
DateTime.Nowformatted as text, plus a line break at the end. - Use
File.AppendAllText("log.txt", logLine)instead ofWriteAllText()so previous entries are preserved. - Include
Environment.NewLineat the end of each entry so future entries start on a new line.
▼ Solution & Explanation
Explanation:
File.AppendAllText("log.txt", logLine): Adds the new line to the end of the file without erasing anything that was written during previous runs.Environment.NewLine: Ensures each log entry starts on its own line, keeping the file readable as it grows.
Exercise 58: Diary Reader (Read Text)
Practice Problem: Write a companion program to Exercise 56 that checks if diary.txt exists using File.Exists(), reads its contents, and displays them back to the console.
Purpose: This exercise helps you practice safely checking for a file’s existence before reading it, avoiding errors when the file has not been created yet.
Given Input: diary.txt contains "Today was a great day!" (written in Exercise 56)
Expected Output: Diary Entry: Today was a great day!
▼ Hint
- Use
File.Exists("diary.txt")to check whether the file is present before trying to read it. - If it exists, use
File.ReadAllText("diary.txt")to load its contents into a string. - If it doesn’t exist, print a friendly message instead of letting the program crash.
▼ Solution & Explanation
Explanation:
File.Exists("diary.txt"): Checks whether the file is present on disk, returningtrueorfalsewithout throwing an error.File.ReadAllText("diary.txt"): Reads the entire contents of the file into a single string, but is only called after confirming the file exists.

Leave a Reply