C# Console

Starter console projects, step by step

These tasks stay simple on purpose. Most of them fit into one Program.cs file and are easy to rebuild for class.

File rule

Every example on this page goes into Program.cs unless the section clearly says otherwise.

Start

How to use the console tasks

This page is for small C# console tasks that are easy to rebuild and test quickly.

For every task below, create a Console App and replace Program.cs with the code block for that section. You do not need extra files unless the section says so.

File rule

All console examples on this page use only Program.cs.

Build order

Read input first, calculate second, print result last.

Quick use

Copy one code block, run it, then change the text or numbers you need.

C# Console

Lesson 1: text output and one integer variable

This is the smallest possible start. You print text, store one whole number, and show it again.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Create a new Console App project.
  2. Open Program.cs and replace the starter code.
  3. Print two lines with Console.WriteLine().
  4. Create one int variable and give it a value.
  5. Print the value, then wait for a key so the window does not close at once.

Quick test

  • Run the app and check that both text lines appear.
  • Change the number and run again. The new value should be printed.
FILE: Program.cs
Program.cs
Console.WriteLine("Hello from C#.");
Console.WriteLine("This is the first lesson.");

int levelNumber = 2;
Console.WriteLine($"Level: {levelNumber}");

Console.WriteLine("Press any key to close.");
Console.ReadKey();
C# Console

Lesson 2: read text and echo it twice

Use Console.ReadLine() to read text from the keyboard and reuse it.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Create a new Console App or reuse the first project.
  2. Ask the user to type one word or sentence.
  3. Store the answer in a string variable.
  4. Print the same text back twice in two different lines.

Quick test

  • Type your name and confirm it appears in both output lines.
  • Type a sentence with spaces and confirm the full sentence is kept.
FILE: Program.cs
Program.cs
Console.Write("Type your name: ");
string name = Console.ReadLine() ?? "";

Console.WriteLine($"Hello, {name}.");
Console.WriteLine($"You typed: {name}");
C# Console

Lesson 3: double a number after parsing text

The user types text first. You then convert the text to an integer and calculate with it.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Ask the user for one whole number.
  2. Use int.TryParse() so the program does not crash on bad input.
  3. Multiply the parsed number by two.
  4. Print the result or show an error message.

Quick test

  • Type 7 and check that the result is 14.
  • Type letters and confirm you get the error text instead of a crash.
FILE: Program.cs
Program.cs
Console.Write("Type a whole number: ");

if (int.TryParse(Console.ReadLine(), out int number))
{
    Console.WriteLine($"Double is {number * 2}.");
}
else
{
    Console.WriteLine("That was not a valid whole number.");
}
C# Console

Lesson 4: sum of two integers

This is the first multi-input task. The only goal is to read two values and add them.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Ask for the first whole number.
  2. Ask for the second whole number.
  3. Use int.TryParse() for both values.
  4. If both values are valid, add them and print the sum.

Quick test

  • Type 4 and 9. The result should be 13.
  • Leave one value invalid and make sure the program reports the problem.
FILE: Program.cs
Program.cs
Console.Write("First whole number: ");
bool okA = int.TryParse(Console.ReadLine(), out int a);

Console.Write("Second whole number: ");
bool okB = int.TryParse(Console.ReadLine(), out int b);

if (okA && okB)
{
    Console.WriteLine($"Sum = {a + b}");
}
else
{
    Console.WriteLine("Please enter valid whole numbers.");
}
C# Console

Basic calculator with four operations and divide-by-zero check

Use one operator character and a switch to choose the calculation.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Read the first number as double.
  2. Read the second number as double.
  3. Ask for the operator: +, -, *, or /.
  4. Use a switch block to calculate the result.
  5. Check for division by zero before dividing.

Quick test

  • Test 8, 2, and / . The result should be 4.
  • Test division by zero and confirm the app shows a clear message.
FILE: Program.cs
Program.cs
Console.Write("First number: ");
bool okA = double.TryParse(Console.ReadLine(), out double a);

Console.Write("Second number: ");
bool okB = double.TryParse(Console.ReadLine(), out double b);

Console.Write("Operator (+, -, *, /): ");
char op = Console.ReadKey().KeyChar;
Console.WriteLine();

if (!okA || !okB)
{
    Console.WriteLine("Invalid number.");
    return;
}

switch (op)
{
    case '+':
        Console.WriteLine($"Result = {a + b}");
        break;
    case '-':
        Console.WriteLine($"Result = {a - b}");
        break;
    case '*':
        Console.WriteLine($"Result = {a * b}");
        break;
    case '/':
        if (b == 0)
        {
            Console.WriteLine("You cannot divide by zero.");
        }
        else
        {
            Console.WriteLine($"Result = {a / b}");
        }
        break;
    default:
        Console.WriteLine("Unknown operator.");
        break;
}
C# Console

Loop calculator with switch menu

Wrap the calculator inside a loop so the user can do more than one calculation.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Show a small menu with numbered choices.
  2. Use a while loop that ends only when the user selects 0.
  3. Read two numbers for each calculation.
  4. Use switch for the menu choice.

Quick test

  • Do one addition and one multiplication without restarting the program.
  • Type 0 and confirm the loop stops cleanly.
FILE: Program.cs
Program.cs
while (true)
{
    Console.WriteLine();
    Console.WriteLine("1 - Add");
    Console.WriteLine("2 - Subtract");
    Console.WriteLine("3 - Multiply");
    Console.WriteLine("4 - Divide");
    Console.WriteLine("0 - Exit");
    Console.Write("Choice: ");
    string choice = Console.ReadLine() ?? "";

    if (choice == "0")
    {
        break;
    }

    double a = ReadNumber("First number: ");
    double b = ReadNumber("Second number: ");

    switch (choice)
    {
        case "1":
            Console.WriteLine($"Result = {a + b}");
            break;
        case "2":
            Console.WriteLine($"Result = {a - b}");
            break;
        case "3":
            Console.WriteLine($"Result = {a * b}");
            break;
        case "4":
            Console.WriteLine(b == 0 ? "You cannot divide by zero." : $"Result = {a / b}");
            break;
        default:
            Console.WriteLine("Unknown menu choice.");
            break;
    }
}

static double ReadNumber(string prompt)
{
    while (true)
    {
        Console.Write(prompt);

        if (double.TryParse(Console.ReadLine(), out double value))
        {
            return value;
        }

        Console.WriteLine("Invalid number. Try again.");
    }
}
C# Console

Small multiplication table with nested loops

This task is good for learning how one loop can run inside another.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Pick a small range, for example 1 to 5.
  2. Use the first loop for rows.
  3. Use the second loop for columns.
  4. Print each product with a fixed width so the table stays lined up.

Quick test

  • Check that the first row starts with 1 2 3 4 5.
  • Check that the value in row 4, column 5 is 20.
FILE: Program.cs
Program.cs
for (int row = 1; row <= 5; row++)
{
    for (int col = 1; col <= 5; col++)
    {
        Console.Write($"{row * col,4}");
    }

    Console.WriteLine();
}
C# Console

One-question quiz with ++ and -- operators

A tiny quiz is enough to show when to add or remove one point.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Create an integer variable for the score.
  2. Ask one question.
  3. If the answer is correct, use points++.
  4. If the answer is wrong, use points--.
  5. Print the final score.

Quick test

  • Type the correct answer and confirm the score becomes 1.
  • Type a wrong answer and confirm the score becomes -1.
FILE: Program.cs
Program.cs
int points = 0;

Console.Write("How many days are in a week? ");
string answer = Console.ReadLine() ?? "";

if (answer == "7")
{
    points++;
    Console.WriteLine("Correct.");
}
else
{
    points--;
    Console.WriteLine("Wrong.");
}

Console.WriteLine($"Score: {points}");
C# Console

Sort exactly 10 numbers and compute average

The goal is to work with a fixed-size array and a simple summary value.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Create an array with 10 slots.
  2. Use a loop to read exactly 10 numbers.
  3. Sort the array with Array.Sort().
  4. Use Average() to calculate the mean value.

Quick test

  • After sorting, the numbers should be in ascending order.
  • Try ten ones. The average should be 1.
FILE: Program.cs
Program.cs
using System.Linq;

double[] numbers = new double[10];

for (int i = 0; i < numbers.Length; i++)
{
    numbers[i] = ReadNumber($"Number {i + 1}: ");
}

Array.Sort(numbers);

Console.WriteLine("Sorted numbers:");
Console.WriteLine(string.Join(", ", numbers));
Console.WriteLine($"Average = {numbers.Average():0.##}");

static double ReadNumber(string prompt)
{
    while (true)
    {
        Console.Write(prompt);

        if (double.TryParse(Console.ReadLine(), out double value))
        {
            return value;
        }

        Console.WriteLine("Invalid number. Try again.");
    }
}
C# Console

Sort space-separated numbers and compute median

This is a common task because it mixes string work, arrays, sorting, and a small formula.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Ask the user to type numbers separated by spaces.
  2. Split the line with Split() and parse each part.
  3. Sort the array.
  4. Find the middle value, or the average of the two middle values for an even count.

Quick test

  • Type 5 1 7. The median should be 5.
  • Type 1 2 3 4. The median should be 2.5.
FILE: Program.cs
Program.cs
using System.Linq;

Console.Write("Numbers separated by spaces: ");
string line = Console.ReadLine() ?? "";

double[] numbers = line
    .Split(' ', StringSplitOptions.RemoveEmptyEntries)
    .Select(double.Parse)
    .ToArray();

Array.Sort(numbers);

double median;
int middle = numbers.Length / 2;

if (numbers.Length % 2 == 1)
{
    median = numbers[middle];
}
else
{
    median = (numbers[middle - 1] + numbers[middle]) / 2;
}

Console.WriteLine("Sorted:");
Console.WriteLine(string.Join(", ", numbers));
Console.WriteLine($"Median = {median:0.##}");
C# Console

Interval validation with repeat loop

This pattern is useful in many tasks. Bad input or out-of-range input should not end the program.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Choose an interval, for example 1 to 100.
  2. Use a loop that keeps asking for input.
  3. Stop only when the number is valid and inside the interval.
  4. Print a success message at the end.

Quick test

  • Type 200 first and then 50. The loop should continue until 50.
  • Type text and confirm the program asks again.
FILE: Program.cs
Program.cs
int number;

while (true)
{
    Console.Write("Type a number from 1 to 100: ");

    if (!int.TryParse(Console.ReadLine(), out number))
    {
        Console.WriteLine("That is not a whole number.");
        continue;
    }

    if (number < 1 || number > 100)
    {
        Console.WriteLine("The number is outside the interval.");
        continue;
    }

    break;
}

Console.WriteLine($"Accepted number: {number}");
C# Console

Leap year check in console

This task is short, but it is asked often. The main thing is to use the rule in the right order.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Read one year as an integer.
  2. A leap year is divisible by 4.
  3. Years divisible by 100 are not leap years, unless they are also divisible by 400.
  4. Print a clear result sentence.

Quick test

  • 2000 should be a leap year.
  • 1900 should not be a leap year.
  • 2024 should be a leap year.
FILE: Program.cs
Program.cs
Console.Write("Year: ");

if (!int.TryParse(Console.ReadLine(), out int year))
{
    Console.WriteLine("Invalid year.");
    return;
}

bool isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

Console.WriteLine(isLeap
    ? $"{year} is a leap year."
    : $"{year} is not a leap year.");
C# Console

Rectangle perimeter and area with optional file export

This combines a small formula task with very basic file output.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Read width and height as positive numbers.
  2. Calculate perimeter and area.
  3. Build one result string so you can both print it and save it.
  4. Ask the user if the result should be written to a text file.

Quick test

  • Width 5 and height 3 should give perimeter 16 and area 15.
  • Choose save and check that the text file is created.
FILE: Program.cs
Program.cs
using System.IO;

double width = ReadPositive("Width: ");
double height = ReadPositive("Height: ");

double perimeter = 2 * (width + height);
double area = width * height;

string result =
    $"Width: {width}\n" +
    $"Height: {height}\n" +
    $"Perimeter: {perimeter}\n" +
    $"Area: {area}";

Console.WriteLine();
Console.WriteLine(result);

Console.Write("Save to rectangle.txt? (y/n): ");
string save = (Console.ReadLine() ?? "").Trim().ToLower();

if (save == "y")
{
    File.WriteAllText("rectangle.txt", result);
    Console.WriteLine("File saved.");
}

static double ReadPositive(string prompt)
{
    while (true)
    {
        Console.Write(prompt);

        if (double.TryParse(Console.ReadLine(), out double value) && value > 0)
        {
            return value;
        }

        Console.WriteLine("Type a positive number.");
    }
}
C# Console

List executable files in the current folder and save the list

This task is good for learning basic work with folders and text files.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Use Environment.CurrentDirectory to get the current folder.
  2. Use Directory.GetFiles() with the pattern *.exe.
  3. Print the file names.
  4. Save the same list to a text file.

Quick test

  • Run the program in a folder that contains at least one .exe file.
  • Check that executables.txt is created.
FILE: Program.cs
Program.cs
using System.IO;

string folder = Environment.CurrentDirectory;
string[] files = Directory.GetFiles(folder, "*.exe");

if (files.Length == 0)
{
    Console.WriteLine("No executable files were found.");
    return;
}

string[] names = files.Select(Path.GetFileName).ToArray();

Console.WriteLine("Executable files:");
foreach (string name in names)
{
    Console.WriteLine($"- {name}");
}

File.WriteAllLines("executables.txt", names);
Console.WriteLine("Saved to executables.txt");
C# Console

Caesar cipher with encryption, decryption and file output

The Caesar cipher is a simple way to practice loops, character work, and helper methods.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Ask for mode: encrypt or decrypt.
  2. Ask for the shift value, for example 3.
  3. Read the source text.
  4. Use one helper method to shift each letter while keeping non-letters unchanged.
  5. Save the final text to a file.

Quick test

  • Encrypt ABC with shift 3. The result should be DEF.
  • Decrypt DEF with shift 3. The result should be ABC.
FILE: Program.cs
Program.cs
using System.IO;

Console.Write("Mode (e = encrypt, d = decrypt): ");
string mode = (Console.ReadLine() ?? "").Trim().ToLower();

Console.Write("Shift: ");
int shift = int.Parse(Console.ReadLine() ?? "0");

Console.Write("Text: ");
string text = Console.ReadLine() ?? "";

if (mode == "d")
{
    shift *= -1;
}

string result = ShiftText(text, shift);

Console.WriteLine($"Result: {result}");
File.WriteAllText("caesar-output.txt", result);
Console.WriteLine("Saved to caesar-output.txt");

static string ShiftText(string text, int shift)
{
    char ShiftChar(char ch, char start, char end)
    {
        int size = end - start + 1;
        int offset = ch - start;
        int moved = (offset + shift) % size;

        if (moved < 0)
        {
            moved += size;
        }

        return (char)(start + moved);
    }

    char[] output = new char[text.Length];

    for (int i = 0; i < text.Length; i++)
    {
        char ch = text[i];

        if (char.IsUpper(ch))
        {
            output[i] = ShiftChar(ch, 'A', 'Z');
        }
        else if (char.IsLower(ch))
        {
            output[i] = ShiftChar(ch, 'a', 'z');
        }
        else
        {
            output[i] = ch;
        }
    }

    return new string(output);
}
C# Console

Resistor color calculator

Sometimes you need a quick text version of the resistor color rule. This example uses three bands.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Create a dictionary for digit values.
  2. Create a dictionary for multiplier values.
  3. Read the first color, second color, and multiplier color.
  4. Combine the first two digits and multiply them.

Quick test

  • Yellow, violet, red should give 4700 ohms.
  • Brown, black, brown should give 100 ohms.
FILE: Program.cs
Program.cs
var digits = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
    ["black"] = 0,
    ["brown"] = 1,
    ["red"] = 2,
    ["orange"] = 3,
    ["yellow"] = 4,
    ["green"] = 5,
    ["blue"] = 6,
    ["violet"] = 7,
    ["gray"] = 8,
    ["white"] = 9
};

var multipliers = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase)
{
    ["black"] = 1,
    ["brown"] = 10,
    ["red"] = 100,
    ["orange"] = 1_000,
    ["yellow"] = 10_000,
    ["green"] = 100_000,
    ["blue"] = 1_000_000
};

Console.Write("First band: ");
string first = Console.ReadLine() ?? "";

Console.Write("Second band: ");
string second = Console.ReadLine() ?? "";

Console.Write("Multiplier band: ");
string multiplier = Console.ReadLine() ?? "";

if (!digits.ContainsKey(first) || !digits.ContainsKey(second) || !multipliers.ContainsKey(multiplier))
{
    Console.WriteLine("Unknown color.");
    return;
}

int value = digits[first] * 10 + digits[second];
double ohms = value * multipliers[multiplier];

Console.WriteLine($"Resistance = {ohms:0} ohms");
C# Console

Mask every third non-space character with regex

This is a nice short task for a regex replacement function with a small counter.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Read a sentence.
  2. Use Regex.Replace() to process every non-space character.
  3. Keep a counter outside the evaluator.
  4. Replace every third non-space character with *.

Quick test

  • The string ABCDEF should become AB*DE*.
  • Spaces should stay unchanged.
FILE: Program.cs
Program.cs
using System.Text.RegularExpressions;

Console.Write("Sentence: ");
string input = Console.ReadLine() ?? "";

int counter = 0;

string result = Regex.Replace(input, @"\S", match =>
{
    counter++;
    return counter % 3 == 0 ? "*" : match.Value;
});

Console.WriteLine(result);
C# Console

Robot vacuum simulation on a grid

The code below keeps the task small. The robot starts in the middle, turns left or right, and moves forward one cell at a time.

Track: C# ConsoleFile: Program.cs

Build steps

  1. Create a 5 x 5 grid.
  2. Store the robot position as x and y.
  3. Store the direction as an index: 0 = North, 1 = East, 2 = South, 3 = West.
  4. Read a command string such as FFRFFL.
  5. Process one command at a time and keep the robot inside the grid.

Quick test

  • Type FFRFF and check that the robot moves from the center.
  • Try many forward moves. The robot must stay inside the grid.
FILE: Program.cs
Program.cs
int size = 5;
int x = 2;
int y = 2;
int direction = 0; // 0 = N, 1 = E, 2 = S, 3 = W

Console.Write("Commands (F, L, R): ");
string commands = (Console.ReadLine() ?? "").ToUpper();

foreach (char command in commands)
{
    switch (command)
    {
        case 'L':
            direction = (direction + 3) % 4;
            break;
        case 'R':
            direction = (direction + 1) % 4;
            break;
        case 'F':
            MoveForward();
            break;
    }
}

for (int row = 0; row < size; row++)
{
    for (int col = 0; col < size; col++)
    {
        Console.Write(row == y && col == x ? "R " : ". ");
    }

    Console.WriteLine();
}

Console.WriteLine($"Final direction: {DirectionName(direction)}");

void MoveForward()
{
    int nextX = x;
    int nextY = y;

    if (direction == 0) nextY--;
    if (direction == 1) nextX++;
    if (direction == 2) nextY++;
    if (direction == 3) nextX--;

    if (nextX >= 0 && nextX < size && nextY >= 0 && nextY < size)
    {
        x = nextX;
        y = nextY;
    }
}

static string DirectionName(int direction) => direction switch
{
    0 => "North",
    1 => "East",
    2 => "South",
    _ => "West"
};