PYnative

Python Programming

  • Learn Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • Quizzes
  • Code Editor ▼
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » C# Exercises » Basic C# Exercises for Beginners: 50+ Coding Problems with Solutions

Basic C# Exercises for Beginners: 50+ Coding Problems with Solutions

Updated on: July 15, 2026 | Leave a Comment

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/else conditions, for/while loops, 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() or Console.WriteLine() to display a prompt asking for the name.
  • Use Console.ReadLine() to capture the input and store it in a string variable.
  • Use string interpolation with a $ prefix to insert the variable into your greeting message.
▼ Solution & Explanation
using System;
namespace UserGreetingApplication
{
    class UserGreeting
    {
        static void Main(string[] args)
        {
            Console.Write("Enter your name: ");
            string name = Console.ReadLine();

            Console.WriteLine($"Hello, {name}! Welcome.");
        }
    }
}Code language: C# (cs)

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 a string, which is stored in the name variable.
  • $"Hello, {name}! Welcome.": Uses string interpolation to insert the value of name directly 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
using System;
namespace AdditionApplication
{
    class BasicAddition
    {
        static void Main(string[] args)
        {
            int firstNumber = 15;
            int secondNumber = 27;
            int sum = firstNumber + secondNumber;

            Console.WriteLine($"Sum = {sum}");
        }
    }
}Code language: C# (cs)

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
using System;
namespace CalculatorApplication
{
    class BasicCalculator
    {
        static void Main(string[] args)
        {
            int firstNumber = 20;
            int secondNumber = 4;

            int sum = firstNumber + secondNumber;
            int difference = firstNumber - secondNumber;
            int product = firstNumber * secondNumber;
            int quotient = firstNumber / secondNumber;

            Console.WriteLine($"Sum = {sum}");
            Console.WriteLine($"Difference = {difference}");
            Console.WriteLine($"Product = {product}");
            Console.WriteLine($"Quotient = {quotient}");
        }
    }
}Code language: C# (cs)

Explanation:

  • int sum = firstNumber + secondNumber;: Adds the two numbers together.
  • int difference = firstNumber - secondNumber;: Subtracts secondNumber from firstNumber.
  • int product = firstNumber * secondNumber;: Multiplies the two numbers using the * operator.
  • int quotient = firstNumber / secondNumber;: Divides firstNumber by secondNumber. 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 double for the Fahrenheit result to avoid losing precision.
  • Multiply by 9.0 instead of 9 so the division is not truncated as integer math.
▼ Solution & Explanation
using System;
namespace TemperatureConversionApplication
{
    class TemperatureConverter
    {
        static void Main(string[] args)
        {
            double celsius = 25;
            double fahrenheit = (celsius * 9.0 / 5.0) + 32;

            Console.WriteLine($"{celsius}°C = {fahrenheit}°F");
        }
    }
}Code language: C# (cs)

Explanation:

  • double celsius = 25;: Stores the input temperature as a double to support decimal precision.
  • (celsius * 9.0 / 5.0) + 32: Applies the Celsius-to-Fahrenheit formula. Using 9.0 and 5.0 ensures 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 double values together first.
  • Divide the total by 3 to get the average.
  • Use Math.Round() if you want to limit the number of decimal places in the output.
▼ Solution & Explanation
using System;
namespace AverageCalculatorApplication
{
    class AverageCalculator
    {
        static void Main(string[] args)
        {
            double firstNumber = 10.5;
            double secondNumber = 20.3;
            double thirdNumber = 15.2;

            double average = (firstNumber + secondNumber + thirdNumber) / 3;
            average = Math.Round(average, 2);

            Console.WriteLine($"Average = {average}");
        }
    }
}Code language: C# (cs)

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
using System;
namespace RemainderFinderApplication
{
    class RemainderFinder
    {
        static void Main(string[] args)
        {
            int firstNumber = 17;
            int secondNumber = 5;
            int remainder = firstNumber % secondNumber;

            Console.WriteLine($"Remainder = {remainder}");
        }
    }
}Code language: C# (cs)

Explanation:

  • int remainder = firstNumber % secondNumber;: The modulus operator % divides firstNumber by secondNumber and 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 (/) by 365 to get the number of full years, then use % to get the days left over.
  • Take the leftover days and divide by 7 to 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
using System;
namespace DateConversionApplication
{
    class DaysConverter
    {
        static void Main(string[] args)
        {
            int totalDays = 400;

            int years = totalDays / 365;
            int daysAfterYears = totalDays % 365;

            int weeks = daysAfterYears / 7;
            int remainingDays = daysAfterYears % 7;

            Console.WriteLine($"Years = {years}");
            Console.WriteLine($"Weeks = {weeks}");
            Console.WriteLine($"Remaining Days = {remainingDays}");
        }
    }
}Code language: C# (cs)

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 % 2 to check the remainder when dividing by 2.
  • If the remainder equals 0, the number is even; otherwise it is odd.
  • Use an if...else statement to print the appropriate message.
▼ Solution & Explanation
using System;
namespace EvenOddApplication
{
    class EvenOddChecker
    {
        static void Main(string[] args)
        {
            int number = 7;

            if (number % 2 == 0)
            {
                Console.WriteLine($"{number} is Even");
            }
            else
            {
                Console.WriteLine($"{number} is Odd");
            }
        }
    }
}Code language: C# (cs)

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 firstNumber in a temporary variable before overwriting it.
  • Assign the value of secondNumber to firstNumber.
  • Assign the temporary variable’s value to secondNumber to complete the swap.
▼ Solution & Explanation
using System;
namespace SwapApplication
{
    class NumberSwapper
    {
        static void Main(string[] args)
        {
            int firstNumber = 5;
            int secondNumber = 10;

            Console.WriteLine($"Before Swap: firstNumber = {firstNumber}, secondNumber = {secondNumber}");

            int temp = firstNumber;
            firstNumber = secondNumber;
            secondNumber = temp;

            Console.WriteLine($"After Swap: firstNumber = {firstNumber}, secondNumber = {secondNumber}");
        }
    }
}Code language: C# (cs)

Explanation:

  • int temp = firstNumber;: Saves the original value of firstNumber in a temporary variable so it is not lost.
  • firstNumber = secondNumber;: Overwrites firstNumber with the value of secondNumber.
  • secondNumber = temp;: Assigns the original value of firstNumber, held in temp, to secondNumber, 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 double if you expect decimal results.
▼ Solution & Explanation
using System;
namespace SimpleInterestApplication
{
    class SimpleInterestCalculator
    {
        static void Main(string[] args)
        {
            double principal = 1000;
            double rate = 5;
            double time = 2;

            double simpleInterest = (principal * rate * time) / 100;

            Console.WriteLine($"Simple Interest = {simpleInterest}");
        }
    }
}Code language: C# (cs)

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 firstNumber and secondNumber first using Math.Max() to find the larger of the two.
  • Compare that result with thirdNumber to find the overall largest value.
  • You could also write this using a series of if statements instead of Math.Max().
▼ Solution & Explanation
using System;
namespace MaximumFinderApplication
{
    class MaximumFinder
    {
        static void Main(string[] args)
        {
            int firstNumber = 12;
            int secondNumber = 45;
            int thirdNumber = 30;

            int max = Math.Max(firstNumber, Math.Max(secondNumber, thirdNumber));

            Console.WriteLine($"Maximum = {max}");
        }
    }
}Code language: C# (cs)

Explanation:

  • Math.Max(secondNumber, thirdNumber): Returns the larger of secondNumber and thirdNumber.
  • Math.Max(firstNumber, ...): Compares firstNumber against 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
using System;
namespace LeapYearApplication
{
    class LeapYearChecker
    {
        static void Main(string[] args)
        {
            int year = 2024;
            bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

            if (isLeapYear)
            {
                Console.WriteLine($"{year} is a Leap Year");
            }
            else
            {
                Console.WriteLine($"{year} is not a Leap Year");
            }
        }
    }
}Code language: C# (cs)

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
using System;
namespace UppercaseConverterApplication
{
    class UppercaseConverter
    {
        static void Main(string[] args)
        {
            string text = "hello world";
            string upperText = text.ToUpper();

            Console.WriteLine(upperText);
        }
    }
}Code language: C# (cs)

Explanation:

  • text.ToUpper(): Calls the built-in ToUpper() 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
using System;
namespace CharacterCounterApplication
{
    class CharacterCounter
    {
        static void Main(string[] args)
        {
            string text = "Programming";
            int count = text.Length;

            Console.WriteLine($"Character Count = {count}");
        }
    }
}Code language: C# (cs)

Explanation:

  • text.Length: Accesses the Length property 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 for loop has three parts: a starting value, a condition, and an update step.
  • Start the counter at 1 and continue while it is less than or equal to 10.
  • Increase the counter by 1 after each iteration using i++.
▼ Solution & Explanation
using System;
namespace CountToTenApplication
{
    class CountToTen
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
}Code language: C# (cs)

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 10 before the loop begins.
  • Use a while loop that continues as long as the counter is greater than 0.
  • Decrease the counter by 1 inside the loop body using i--.
▼ Solution & Explanation
using System;
namespace CountdownApplication
{
    class Countdown
    {
        static void Main(string[] args)
        {
            int i = 10;

            while (i >= 1)
            {
                Console.WriteLine(i);
                i--;
            }
        }
    }
}Code language: C# (cs)

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 for loop with the counter running from 1 to 10.
  • Inside the loop, multiply number by the current counter value.
  • Use string interpolation to format each line consistently.
▼ Solution & Explanation
using System;
namespace MultiplicationTableApplication
{
    class MultiplicationTable
    {
        static void Main(string[] args)
        {
            int number = 5;

            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine($"{number} x {i} = {number * i}");
            }
        }
    }
}Code language: C# (cs)

Explanation:

  • for (int i = 1; i <= 10; i++): Loops the counter i from 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 = 0 before the loop.
  • Use a for loop from 1 to n, adding each value to sum.
  • Print sum after the loop finishes.
▼ Solution & Explanation
using System;
namespace SumOfNNumbersApplication
{
    class SumCalculator
    {
        static void Main(string[] args)
        {
            int n = 10;
            int sum = 0;

            for (int i = 1; i <= n; i++)
            {
                sum += i;
            }

            Console.WriteLine($"Sum = {sum}");
        }
    }
}Code language: C# (cs)

Explanation:

  • int sum = 0;: Initializes the accumulator to zero before the loop starts.
  • sum += i;: Adds the current loop value to sum on 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, not 0, since you will be multiplying.
  • Use a for loop from 1 to n, multiplying factorial by each value.
  • Use a long instead of int if you expect larger values of n.
▼ Solution & Explanation
using System;
namespace FactorialApplication
{
    class FactorialCalculator
    {
        static void Main(string[] args)
        {
            int n = 5;
            long factorial = 1;

            for (int i = 1; i <= n; i++)
            {
                factorial *= i;
            }

            Console.WriteLine($"Factorial = {factorial}");
        }
    }
}Code language: C# (cs)

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 of int because factorial results grow very quickly and can exceed the range of int.

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 1 to 50.
  • Inside the loop, use % 2 == 0 to 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 2 and increase by 2 each time.
▼ Solution & Explanation
using System;
namespace EvenNumbersApplication
{
    class EvenNumbersPrinter
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 50; i++)
            {
                if (i % 2 == 0)
                {
                    Console.WriteLine(i);
                }
            }
        }
    }
}Code language: C# (cs)

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 the if statement.

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 foreach loop to iterate through the array without needing an index.
  • Print each value inside the loop body using Console.WriteLine().
▼ Solution & Explanation
using System;
namespace ArrayInitializationApplication
{
    class ArrayInitializer
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[5] { 10, 20, 30, 40, 50 };

            foreach (int number in numbers)
            {
                Console.WriteLine(number);
            }
        }
    }
}Code language: C# (cs)

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 to number in 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 min whenever you find a smaller value.
  • Update max whenever you find a larger value.
▼ Solution & Explanation
using System;
namespace MinMaxFinderApplication
{
    class MinMaxFinder
    {
        static void Main(string[] args)
        {
            int[] numbers = { 12, 45, 3, 67, 21 };

            int min = numbers[0];
            int max = numbers[0];

            foreach (int number in numbers)
            {
                if (number < min)
                {
                    min = number;
                }
                if (number > max)
                {
                    max = number;
                }
            }

            Console.WriteLine($"Minimum = {min}");
            Console.WriteLine($"Maximum = {max}");
        }
    }
}Code language: C# (cs)

Explanation:

  • int min = numbers[0]; int max = numbers[0];: Initializes both trackers using the first element as a starting point.
  • if (number < min): Updates min whenever a smaller value is found while looping.
  • if (number > max): Updates max whenever 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.Length to find the total number of elements.
  • Start a for loop at the last valid index (Length - 1) and count down to 0.
  • Print each element using its index inside the loop.
▼ Solution & Explanation
using System;
namespace ArrayReverserApplication
{
    class ArrayReverser
    {
        static void Main(string[] args)
        {
            string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };

            for (int i = fruits.Length - 1; i >= 0; i--)
            {
                Console.WriteLine(fruits[i]);
            }
        }
    }
}Code language: C# (cs)

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 foreach loop to add each array element to sum.
  • Print sum once the loop finishes.
▼ Solution & Explanation
using System;
namespace ArraySumApplication
{
    class ArraySum
    {
        static void Main(string[] args)
        {
            double[] numbers = { 10.5, 20.3, 5.2, 8.0 };
            double sum = 0;

            foreach (double number in numbers)
            {
                sum += number;
            }

            Console.WriteLine($"Sum = {sum}");
        }
    }
}Code language: C# (cs)

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 an int using int.Parse().
  • Loop through the array with a regular for loop so you have access to the index.
  • When a match is found, store the index and stop searching with break.
▼ Solution & Explanation
using System;
namespace ElementSearchApplication
{
    class ElementSearcher
    {
        static void Main(string[] args)
        {
            int[] numbers = { 4, 8, 15, 16, 23, 42 };

            Console.Write("Enter a number to search: ");
            int target = int.Parse(Console.ReadLine());

            int index = -1;
            for (int i = 0; i < numbers.Length; i++)
            {
                if (numbers[i] == target)
                {
                    index = i;
                    break;
                }
            }

            if (index != -1)
            {
                Console.WriteLine($"{target} found at index {index}");
            }
            else
            {
                Console.WriteLine($"{target} not found in the array");
            }
        }
    }
}Code language: C# (cs)

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 with break.

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 use List<T>.
  • Create an empty list with new List<int>().
  • Use a loop to call Add() multiple times, then print Count.
▼ Solution & Explanation
using System;
using System.Collections.Generic;

namespace DynamicListApplication
{
    class DynamicIntegerList
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>();

            for (int i = 1; i <= 5; i++)
            {
                numbers.Add(i * 10);
            }

            Console.WriteLine($"Total Items = {numbers.Count}");
        }
    }
}Code language: C# (cs)

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
using System;
using System.Collections.Generic;

namespace DuplicateRemoverApplication
{
    class DuplicateRemover
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };
            List<int> uniqueNumbers = new List<int>();

            foreach (int number in numbers)
            {
                if (!uniqueNumbers.Contains(number))
                {
                    uniqueNumbers.Add(number);
                }
            }

            Console.WriteLine("Unique Numbers: " + string.Join(", ", uniqueNumbers));
        }
    }
}Code language: C# (cs)

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
using System;
namespace StringReverserApplication
{
    class StringReverser
    {
        static string ReverseString(string input)
        {
            char[] characters = input.ToCharArray();
            Array.Reverse(characters);
            return new string(characters);
        }

        static void Main(string[] args)
        {
            string text = "Hello";
            string reversed = ReverseString(text);

            Console.WriteLine(reversed);
        }
    }
}Code language: C# (cs)

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 false immediately for those.
  • Loop from 2 up 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, return true.
▼ Solution & Explanation
using System;
namespace PrimeCheckerApplication
{
    class PrimeChecker
    {
        static bool IsPrime(int number)
        {
            if (number < 2)
            {
                return false;
            }

            for (int i = 2; i <= Math.Sqrt(number); i++)
            {
                if (number % i == 0)
                {
                    return false;
                }
            }

            return true;
        }

        static void Main(string[] args)
        {
            int number = 17;
            bool result = IsPrime(number);

            Console.WriteLine($"{number} is Prime: {result}");
        }
    }
}Code language: C# (cs)

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 Car class with three public properties using auto-implemented property syntax, e.g. public string Make { get; set; }.
  • In Main, create a new Car object and assign values to each property.
  • Print each property using string interpolation.
▼ Solution & Explanation
using System;
namespace CarApplication
{
    class Car
    {
        public string Make { get; set; }
        public string Model { get; set; }
        public int Year { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Car myCar = new Car();
            myCar.Make = "Toyota";
            myCar.Model = "Corolla";
            myCar.Year = 2022;

            Console.WriteLine($"Make: {myCar.Make}");
            Console.WriteLine($"Model: {myCar.Model}");
            Console.WriteLine($"Year: {myCar.Year}");
        }
    }
}Code language: C# (cs)

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 the Car class, called an object.
  • myCar.Make = "Toyota";: Sets the object’s Make property using dot notation.
  • class Program: A separate class holding Main, kept apart from the Car class 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 the Car class with a void return type.
  • Inside the method, use Make and Model directly since they belong to the same object.
  • Call myCar.Drive() from Main after setting the properties.
▼ Solution & Explanation
using System;
namespace CarMethodsApplication
{
    class Car
    {
        public string Make { get; set; }
        public string Model { get; set; }
        public int Year { get; set; }

        public void Drive()
        {
            Console.WriteLine($"The {Make} {Model} is driving!");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Car myCar = new Car();
            myCar.Make = "Toyota";
            myCar.Model = "Corolla";
            myCar.Year = 2022;

            myCar.Drive();
        }
    }
}Code language: C# (cs)

Explanation:

  • public void Drive(): Defines an instance method that belongs to every Car object and returns no value.
  • $"The {Make} {Model} is driving!": Reads the object’s own Make and Model properties directly, without needing them passed in as arguments.
  • myCar.Drive();: Calls the method on the specific myCar object 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 title and author as 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
using System;
namespace BookApplication
{
    class Book
    {
        public string Title { get; set; }
        public string Author { get; set; }

        public Book(string title, string author)
        {
            Title = title;
            Author = author;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Book myBook = new Book("1984", "George Orwell");

            Console.WriteLine($"Title: {myBook.Title}");
            Console.WriteLine($"Author: {myBook.Author}");
        }
    }
}Code language: C# (cs)

Explanation:

  • public Book(string title, string author): Defines a constructor that runs automatically when a new Book is created, requiring both parameters.
  • Title = title; Author = author;: Assigns the incoming constructor parameters to the object’s properties.
  • new Book("1984", "George Orwell"): Creates a Book object 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 balance as private so it cannot be changed directly from outside the class.
  • In Deposit(), add the given amount to balance.
  • In Withdraw(), check that balance is sufficient before subtracting the amount, and provide a public method or property to read the current balance.
▼ Solution & Explanation
using System;
namespace BankAccountApplication
{
    class BankAccount
    {
        private double balance;

        public void Deposit(double amount)
        {
            balance += amount;
        }

        public void Withdraw(double amount)
        {
            if (amount <= balance)
            {
                balance -= amount;
            }
            else
            {
                Console.WriteLine("Insufficient funds.");
            }
        }

        public double GetBalance()
        {
            return balance;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            BankAccount account = new BankAccount();
            account.Deposit(500);
            account.Withdraw(200);

            Console.WriteLine($"Balance = {account.GetBalance()}");
        }
    }
}Code language: C# (cs)

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 virtual so it can be overridden.
  • In the Dog class, use : Animal to inherit from it, and mark the overriding method with override.
  • Assign a Dog object to an Animal variable to see the overridden method run.
▼ Solution & Explanation
using System;
namespace AnimalApplication
{
    class Animal
    {
        public virtual void MakeSound()
        {
            Console.WriteLine("Some generic animal sound");
        }
    }

    class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Bark!");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Animal myDog = new Dog();
            myDog.MakeSound();
        }
    }
}Code language: C# (cs)

Explanation:

  • public virtual void MakeSound(): Marks the base class method as overridable by any derived class.
  • class Dog : Animal: Declares that Dog inherits all members from Animal.
  • public override void MakeSound(): Replaces the base class behavior with the Dog-specific implementation.
  • Animal myDog = new Dog();: Even though the variable type is Animal, calling MakeSound() runs the overridden version from Dog.

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 X and Y as public fields or properties inside the struct.
  • The distance from the origin follows the Pythagorean formula: sqrt(X^2 + Y^2).
  • Use Math.Sqrt() together with Math.Pow(), or simply multiply each value by itself.
▼ Solution & Explanation
using System;
namespace PointApplication
{
    struct Point
    {
        public double X;
        public double Y;

        public double DistanceFromOrigin()
        {
            return Math.Sqrt(X * X + Y * Y);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Point point = new Point { X = 3, Y = 4 };

            Console.WriteLine($"Distance = {point.DistanceFromOrigin()}");
        }
    }
}Code language: C# (cs)

Explanation:

  • struct Point: Defines a value type that groups the X and Y coordinates 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 a Point instance 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, and b and assigns them to the properties.
  • Marking the whole struct as readonly reinforces that none of its members can change after construction.
▼ Solution & Explanation
using System;
namespace ColorApplication
{
    readonly struct Color
    {
        public int R { get; }
        public int G { get; }
        public int B { get; }

        public Color(int r, int g, int b)
        {
            R = r;
            G = g;
            B = b;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Color myColor = new Color(255, 0, 0);

            Console.WriteLine($"R: {myColor.R}");
            Console.WriteLine($"G: {myColor.G}");
            Console.WriteLine($"B: {myColor.B}");
        }
    }
}Code language: C# (cs)

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 where R, G, and B can 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 Product instances with the same values.
  • Compare them with ==. Unlike a class, records compare their contents rather than their memory reference.
▼ Solution & Explanation
using System;
namespace ProductApplication
{
    record Product(string Name, decimal Price);

    class Program
    {
        static void Main(string[] args)
        {
            Product prod1 = new Product("Book", 15.99m);
            Product prod2 = new Product("Book", 15.99m);

            Console.WriteLine(prod1 == prod2);
        }
    }
}Code language: C# (cs)

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 the Grade changed.
  • Print both records to confirm the original was not modified.
▼ Solution & Explanation
using System;
namespace StudentApplication
{
    record Student(string Name, string Grade);

    class Program
    {
        static void Main(string[] args)
        {
            Student student1 = new Student("Alice", "B");
            Student student2 = student1 with { Grade = "A" };

            Console.WriteLine($"Name: {student1.Name}, Grade: {student1.Grade}");
            Console.WriteLine($"Name: {student2.Name}, Grade: {student2.Grade}");
        }
    }
}Code language: C# (cs)

Explanation:

  • student1 with { Grade = "A" }: Creates a brand new Student record that copies all values from student1, except Grade, which is replaced with the new value.
  • student1.Grade: Remains "B" after the with expression, 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 while loop to keep showing the menu until the user chooses to exit.
  • Read the menu choice with Console.ReadLine() and use a switch statement to handle each option.
  • Use Add() and Remove() on the list, and a foreach loop to print all items when viewing the list.
▼ Solution & Explanation
using System;
using System.Collections.Generic;

namespace GroceryListApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> groceryList = new List<string>();
            bool running = true;

            while (running)
            {
                Console.WriteLine("1. Add item  2. Remove item  3. View list  4. Exit");
                Console.Write("Choose an option: ");
                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        Console.Write("Enter item to add: ");
                        string itemToAdd = Console.ReadLine();
                        groceryList.Add(itemToAdd);
                        break;

                    case "2":
                        Console.Write("Enter item to remove: ");
                        string itemToRemove = Console.ReadLine();
                        groceryList.Remove(itemToRemove);
                        break;

                    case "3":
                        Console.WriteLine("Grocery List:");
                        foreach (string item in groceryList)
                        {
                            Console.WriteLine("- " + item);
                        }
                        break;

                    case "4":
                        running = false;
                        break;
                }
            }
        }
    }
}Code language: C# (cs)

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 the while loop, 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 or Add().
  • 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
using System;
using System.Collections.Generic;

namespace ContactDirectoryApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> contacts = new Dictionary<string, string>
            {
                { "Alice", "555-1234" },
                { "Bob", "555-5678" }
            };

            Console.Write("Enter a name to search: ");
            string searchName = Console.ReadLine();

            if (contacts.TryGetValue(searchName, out string number))
            {
                Console.WriteLine($"{searchName}'s number: {number}");
            }
            else
            {
                Console.WriteLine($"{searchName} was not found in the directory.");
            }
        }
    }
}Code language: C# (cs)

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, returning true or false instead 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 use HashSet<T>.
  • The Add() method on a HashSet returns true if the item was added and false if it was already present.
  • Use that return value inside an if statement to print the correct message for each ID.
▼ Solution & Explanation
using System;
using System.Collections.Generic;

namespace StudentRegistrationApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            HashSet<int> studentIds = new HashSet<int>();
            int[] idsToRegister = { 101, 102, 101, 103 };

            foreach (int id in idsToRegister)
            {
                if (studentIds.Add(id))
                {
                    Console.WriteLine($"{id} registered successfully.");
                }
                else
                {
                    Console.WriteLine($"{id} is already registered.");
                }
            }
        }
    }
}Code language: C# (cs)

Explanation:

  • HashSet<int> studentIds = new HashSet<int>();: Creates a collection that automatically rejects duplicate values.
  • studentIds.Add(id): Attempts to add the ID, returning true if it was new and false if 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 > 0 before popping, so you don’t try to undo when the stack is empty.
▼ Solution & Explanation
using System;
using System.Collections.Generic;

namespace TextEditorApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack<string> history = new Stack<string>();
            string[] actions = { "Hello", "World", "undo" };

            foreach (string action in actions)
            {
                if (action == "undo")
                {
                    if (history.Count > 0)
                    {
                        string removedWord = history.Pop();
                        Console.WriteLine($"Undo: removed \"{removedWord}\"");
                    }
                }
                else
                {
                    history.Push(action);
                    Console.WriteLine($"Typed: {action}");
                }
            }

            Console.WriteLine("Remaining words:");
            foreach (string word in history)
            {
                Console.WriteLine(word);
            }
        }
    }
}Code language: C# (cs)

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 calling Pop() 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 while loop that continues as long as Count > 0.
  • Use Dequeue() inside the loop to remove and serve the customer at the front of the line.
▼ Solution & Explanation
using System;
using System.Collections.Generic;

namespace BankLineApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue<string> customers = new Queue<string>();
            customers.Enqueue("Alice");
            customers.Enqueue("Bob");
            customers.Enqueue("Charlie");

            while (customers.Count > 0)
            {
                string currentCustomer = customers.Dequeue();
                Console.WriteLine($"Serving: {currentCustomer}");
            }
        }
    }
}Code language: C# (cs)

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 using Add().
  • Unlike a regular Dictionary, a SortedList automatically keeps its keys in sorted order internally.
  • Loop through it with foreach using a KeyValuePair to print each entry.
▼ Solution & Explanation
using System;
using System.Collections.Generic;

namespace InventoryApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedList<string, string> inventory = new SortedList<string, string>();
            inventory.Add("B002", "Gadget");
            inventory.Add("A001", "Widget");
            inventory.Add("C003", "Gizmo");

            foreach (KeyValuePair<string, string> item in inventory)
            {
                Console.WriteLine($"{item.Key}: {item.Value}");
            }
        }
    }
}Code language: C# (cs)

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.Key and product.Value inside a string interpolation to build the message.
▼ Solution & Explanation
using System;
using System.Collections.Generic;

namespace ProductPriceApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, double> products = new Dictionary<string, double>
            {
                { "Laptop", 999.99 },
                { "Mouse", 25.50 },
                { "Keyboard", 45.00 }
            };

            foreach (KeyValuePair<string, double> product in products)
            {
                Console.WriteLine($"Product: {product.Key} costs ${product.Value}");
            }
        }
    }
}Code language: C# (cs)

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 a bool.
  • Use Clear() to remove every element from the list at once.
  • Print Count after clearing to confirm the list is now empty.
▼ Solution & Explanation
using System;
using System.Collections.Generic;

namespace CollectionClearingApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> items = new List<string> { "Pen", "Notebook", "Eraser" };

            bool hasNotebook = items.Contains("Notebook");
            Console.WriteLine($"Contains Notebook: {hasNotebook}");

            items.Clear();
            Console.WriteLine($"Item Count After Clear: {items.Count}");
        }
    }
}Code language: C# (cs)

Explanation:

  • items.Contains("Notebook"): Checks whether the value exists anywhere in the list and returns true or false.
  • items.Clear();: Removes all elements from the list, leaving it empty but still usable.
  • items.Count: Confirms the list is empty by returning 0 after 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
using System;
using System.Collections.Generic;
using System.Linq;

namespace EvenFilterApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = Enumerable.Range(1, 20).ToList();
            var evenNumbers = numbers.Where(n => n % 2 == 0);

            foreach (int number in evenNumbers)
            {
                Console.WriteLine(number);
            }
        }
    }
}Code language: C# (cs)

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 to true.
  • var evenNumbers = ...: Stores the filtered sequence, which is then iterated with a foreach loop 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
using System;
using System.Collections.Generic;
using System.Linq;

namespace TopScorersApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> scores = new List<int> { 75, 88, 92, 60, 85 };
            var topScores = scores.Where(s => s > 80).OrderByDescending(s => s);

            foreach (int score in topScores)
            {
                Console.WriteLine(score);
            }
        }
    }
}Code language: C# (cs)

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 foreach to print each uppercase city name.
▼ Solution & Explanation
using System;
using System.Collections.Generic;
using System.Linq;

namespace CityNameApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> cities = new List<string> { "london", "paris", "tokyo" };
            var upperCities = cities.Select(c => c.ToUpper());

            foreach (string city in upperCities)
            {
                Console.WriteLine(city);
            }
        }
    }
}Code language: C# (cs)

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 original cities list.

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
using System;
using System.Collections.Generic;
using System.Linq;

namespace PriceAggregationApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<double> prices = new List<double> { 19.99, 5.49, 42.00, 12.75 };

            Console.WriteLine($"Sum = {prices.Sum()}");
            Console.WriteLine($"Average = {prices.Average()}");
            Console.WriteLine($"Min = {prices.Min()}");
            Console.WriteLine($"Max = {prices.Max()}");
        }
    }
}Code language: C# (cs)

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() returns null for a string list, so check for that before printing.
▼ Solution & Explanation
using System;
using System.Collections.Generic;
using System.Linq;

namespace FirstMatchApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string> { "Michael", "Sarah", "James", "Laura" };
            string firstMatch = names.FirstOrDefault(n => n.StartsWith("J"));

            if (firstMatch != null)
            {
                Console.WriteLine($"First match: {firstMatch}");
            }
            else
            {
                Console.WriteLine("No name starting with 'J' was found.");
            }
        }
    }
}Code language: C# (cs)

Explanation:

  • names.FirstOrDefault(n => n.StartsWith("J")): Scans the list and returns the first name that starts with “J”, or null if 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.Now to get the current date and time.
  • Call .ToString() on it with a custom format string like "MM/dd/yyyy HH:mm:ss".
  • HH represents a 24-hour clock, while hh would represent a 12-hour clock.
▼ Solution & Explanation
using System;
namespace CurrentTimeApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("MM/dd/yyyy HH:mm:ss");

            Console.WriteLine(formattedTime);
        }
    }
}Code language: C# (cs)

Explanation:

  • DateTime.Now: Retrieves the current date and time from the system clock.
  • now.ToString("MM/dd/yyyy HH:mm:ss"): Converts the DateTime value 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 a DateTime value.
  • Subtracting one DateTime from another produces a TimeSpan.
  • Use the TimeSpan‘s .Days property to get the whole number of days between the two dates.
▼ Solution & Explanation
using System;
namespace AgeCalculatorApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string birthDateText = "1995-06-15";
            DateTime birthDate = DateTime.Parse(birthDateText);

            TimeSpan age = DateTime.Today - birthDate;

            Console.WriteLine($"You are {age.Days} days old.");
        }
    }
}Code language: C# (cs)

Explanation:

  • DateTime.Parse(birthDateText): Converts the text representation of the birthdate into a proper DateTime value.
  • DateTime.Today - birthDate: Subtracts the two dates, producing a TimeSpan that represents the difference between them.
  • age.Days: Reads the total number of whole days contained in the TimeSpan.

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 DateTime has a DayOfWeek property that returns the day name automatically.
  • Format the date using .ToString("MM/dd/yyyy") for a clean display.
▼ Solution & Explanation
using System;
namespace DateArithmeticApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime futureDate = DateTime.Today.AddDays(45);

            Console.WriteLine($"45 days from today is {futureDate:MM/dd/yyyy}, which falls on a {futureDate.DayOfWeek}.");
        }
    }
}Code language: C# (cs)

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 calculated DateTime value.

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 an int with int.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
using System;
namespace DaysInMonthApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a year: ");
            int year = int.Parse(Console.ReadLine());

            Console.Write("Enter a month (1-12): ");
            int month = int.Parse(Console.ReadLine());

            int daysInMonth = DateTime.DaysInMonth(year, month);
            string monthName = new DateTime(year, month, 1).ToString("MMMM");

            Console.WriteLine($"{monthName} {year} has {daysInMonth} days.");
        }
    }
}Code language: C# (cs)

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
using System;
using System.IO;

namespace DiaryWriterApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Write your diary entry: ");
            string entry = Console.ReadLine();

            File.WriteAllText("diary.txt", entry);

            Console.WriteLine("Your diary entry has been saved.");
        }
    }
}Code language: C# (cs)

Explanation:

  • using System.IO;: Imports the namespace that contains the File class and its file handling methods.
  • File.WriteAllText("diary.txt", entry): Writes the entered text to diary.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.Now formatted as text, plus a line break at the end.
  • Use File.AppendAllText("log.txt", logLine) instead of WriteAllText() so previous entries are preserved.
  • Include Environment.NewLine at the end of each entry so future entries start on a new line.
▼ Solution & Explanation
using System;
using System.IO;

namespace LogAppendApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string timestamp = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
            string logLine = $"Log entry added at {timestamp}" + Environment.NewLine;

            File.AppendAllText("log.txt", logLine);

            Console.WriteLine($"Log entry added at {timestamp}");
        }
    }
}Code language: C# (cs)

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
using System;
using System.IO;

namespace DiaryReaderApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            if (File.Exists("diary.txt"))
            {
                string entry = File.ReadAllText("diary.txt");
                Console.WriteLine($"Diary Entry: {entry}");
            }
            else
            {
                Console.WriteLine("No diary entry was found. Write one first.");
            }
        }
    }
}Code language: C# (cs)

Explanation:

  • File.Exists("diary.txt"): Checks whether the file is present on disk, returning true or false without 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.

Filed Under: C# Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

C# Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: C# Exercises
TweetF  sharein  shareP  Pin

  C# Exercises

  • C# Exercise for Beginners
  • C# Loops Exercise
  • C# Array Exercise
  • C# String Exercise
  • C# OOP Exercise
  • C# Structs, Records and Enums Exercise
  • C# Collections Exercise
  • C# List Exercise
  • C# Dictionary Exercise
  • C# LINQ Exercise
  • C# Exception Handling Exercise
  • C# File Handling Exercise
  • C# Date and Time Exercise
  • C# Generics Exercise
  • C# Lambda Expressions Exercise
  • C# Delegates and Events Exercise
  • C# Extension Methods Exercise
  • C# Regex Exercise
  • C# Pattern Matching Exercise
  • C# Iterators and Yield Exercise
  • C# Indexers and Operator Overloading Exercise
  • C# Random Data Generation Exercise

All Coding Exercises

Python Exercises C Exercises C++ Exercises Java Exercises C# Exercises

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com