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.
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.
Build steps
- Create a new Console App project.
- Open Program.cs and replace the starter code.
- Print two lines with
Console.WriteLine(). - Create one
intvariable and give it a value. - 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
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();
Lesson 2: read text and echo it twice
Use Console.ReadLine() to read text from the keyboard and reuse it.
Build steps
- Create a new Console App or reuse the first project.
- Ask the user to type one word or sentence.
- Store the answer in a
stringvariable. - 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
Console.Write("Type your name: ");
string name = Console.ReadLine() ?? "";
Console.WriteLine($"Hello, {name}.");
Console.WriteLine($"You typed: {name}");
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.
Build steps
- Ask the user for one whole number.
- Use
int.TryParse()so the program does not crash on bad input. - Multiply the parsed number by two.
- 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
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.");
}
Lesson 4: sum of two integers
This is the first multi-input task. The only goal is to read two values and add them.
Build steps
- Ask for the first whole number.
- Ask for the second whole number.
- Use
int.TryParse()for both values. - 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
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.");
}
Basic calculator with four operations and divide-by-zero check
Use one operator character and a switch to choose the calculation.
Build steps
- Read the first number as
double. - Read the second number as
double. - Ask for the operator:
+,-,*, or/. - Use a
switchblock to calculate the result. - 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
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;
}
Loop calculator with switch menu
Wrap the calculator inside a loop so the user can do more than one calculation.
Build steps
- Show a small menu with numbered choices.
- Use a
whileloop that ends only when the user selects 0. - Read two numbers for each calculation.
- Use
switchfor 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
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.");
}
}
Small multiplication table with nested loops
This task is good for learning how one loop can run inside another.
Build steps
- Pick a small range, for example 1 to 5.
- Use the first loop for rows.
- Use the second loop for columns.
- 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
for (int row = 1; row <= 5; row++)
{
for (int col = 1; col <= 5; col++)
{
Console.Write($"{row * col,4}");
}
Console.WriteLine();
}
One-question quiz with ++ and -- operators
A tiny quiz is enough to show when to add or remove one point.
Build steps
- Create an integer variable for the score.
- Ask one question.
- If the answer is correct, use
points++. - If the answer is wrong, use
points--. - 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
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}");
Sort exactly 10 numbers and compute average
The goal is to work with a fixed-size array and a simple summary value.
Build steps
- Create an array with 10 slots.
- Use a loop to read exactly 10 numbers.
- Sort the array with
Array.Sort(). - 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
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.");
}
}
Sort space-separated numbers and compute median
This is a common task because it mixes string work, arrays, sorting, and a small formula.
Build steps
- Ask the user to type numbers separated by spaces.
- Split the line with
Split()and parse each part. - Sort the array.
- 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
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.##}");
Interval validation with repeat loop
This pattern is useful in many tasks. Bad input or out-of-range input should not end the program.
Build steps
- Choose an interval, for example 1 to 100.
- Use a loop that keeps asking for input.
- Stop only when the number is valid and inside the interval.
- 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
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}");
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.
Build steps
- Read one year as an integer.
- A leap year is divisible by 4.
- Years divisible by 100 are not leap years, unless they are also divisible by 400.
- 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
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.");
Rectangle perimeter and area with optional file export
This combines a small formula task with very basic file output.
Build steps
- Read width and height as positive numbers.
- Calculate perimeter and area.
- Build one result string so you can both print it and save it.
- 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
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.");
}
}
List executable files in the current folder and save the list
This task is good for learning basic work with folders and text files.
Build steps
- Use
Environment.CurrentDirectoryto get the current folder. - Use
Directory.GetFiles()with the pattern*.exe. - Print the file names.
- 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.txtis created.
FILE: 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");
Caesar cipher with encryption, decryption and file output
The Caesar cipher is a simple way to practice loops, character work, and helper methods.
Build steps
- Ask for mode: encrypt or decrypt.
- Ask for the shift value, for example 3.
- Read the source text.
- Use one helper method to shift each letter while keeping non-letters unchanged.
- 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
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);
}
Resistor color calculator
Sometimes you need a quick text version of the resistor color rule. This example uses three bands.
Build steps
- Create a dictionary for digit values.
- Create a dictionary for multiplier values.
- Read the first color, second color, and multiplier color.
- 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
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");
Mask every third non-space character with regex
This is a nice short task for a regex replacement function with a small counter.
Build steps
- Read a sentence.
- Use
Regex.Replace()to process every non-space character. - Keep a counter outside the evaluator.
- Replace every third non-space character with
*.
Quick test
- The string ABCDEF should become AB*DE*.
- Spaces should stay unchanged.
FILE: 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);
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.
Build steps
- Create a 5 x 5 grid.
- Store the robot position as
xandy. - Store the direction as an index: 0 = North, 1 = East, 2 = South, 3 = West.
- Read a command string such as
FFRFFL. - 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
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"
};