Console Output Methods
Console.WriteLine()
Prints text and moves to a new line.
Console.WriteLine("Hello World!");
Console.WriteLine("This is on a new line");
Output:
Hello World!
This is on a new line
Console.Write()
Prints text without moving to a new line.
Console.Write("Hello ");
Console.Write("World!");
Output:
Hello World!
Combining Output
Console.Write("Enter your name: "); // Prompt stays on same line
string sName = Console.ReadLine();
Console.WriteLine("Welcome, " + sName + "!");
Printing Special Characters
Escape Sequences
Escape Sequence | Description | Example |
---|---|---|
\n |
New line | "Line 1\nLine 2" |
\t |
Tab | "Name\tAge" |
\\ |
Backslash | "C:\\Files" |
\" |
Double quote | "She said \"Hi\"" |
\' |
Single quote | 'It\'s' |
// New line
Console.WriteLine("Hello\nWorld");
// Output:
// Hello
// World
// Tab
Console.WriteLine("Name\tAge\tGrade");
Console.WriteLine("John\t20\tA");
// Output:
// Name Age Grade
// John 20 A
// Backslash
Console.WriteLine("File path: C:\\Users\\Documents");
// Output: File path: C:\Users\Documents
Verbatim Strings
Use @
to ignore escape sequences:
string sPath = @"C:\Users\Documents\file.txt";
Console.WriteLine(sPath);
// Output: C:\Users\Documents\file.txt
string sMultiLine = @"Line 1
Line 2
Line 3";
Console.WriteLine(sMultiLine);
ASCII Art Examples
Example 1: Duck (From Worksheet 1)
Console.WriteLine(" _");
Console.WriteLine(" ___(.)<");
Console.WriteLine(" \\____) ");
Console.WriteLine(" Duck");
Example 2: Butterfly (From Worksheet 1)
Console.WriteLine(" _ \" _ ");
Console.WriteLine(" (_\\|/_)");
Console.WriteLine(" (/|\\)");
Console.WriteLine(" Butterfly");
Example 3: Flower and Dog (From Practical Test 1)
Console.WriteLine(" _/)");
Console.WriteLine(" .-(_(=:");
Console.WriteLine(" | \\)");
Console.WriteLine(" (\\_ |");
Console.WriteLine(" :=)_)-| _/)");
Console.WriteLine(" (/ |-(_(=:");
Console.WriteLine(" | \\)");
Console.WriteLine(" ____|____");
Console.WriteLine(" [ ]");
Console.WriteLine(" \\ /");
Console.WriteLine(" \\ /");
Console.WriteLine(" \\___/");
Console.WriteLine("Flower.");
Console.WriteLine(" |");
Console.WriteLine(" .-. / \\");
Console.WriteLine(" ((\")) .|||.");
Console.WriteLine(" ==)-/_\\--o /| |\\");
Console.WriteLine(" /___\\ / | | \\");
Console.WriteLine("......d b....\\/\\|||/\\/........");
Console Input Methods
Console.ReadLine()
Reads a complete line of text (returns string).
Console.Write("Enter your name: ");
string sName = Console.ReadLine();
Console.WriteLine("Hello, " + sName + "!");
Console.ReadKey()
Reads a single key press (doesn't display in console by default).
Console.WriteLine("Press any key to continue...");
Console.ReadKey(); // Waits for any key press
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
Console.Read()
Reads a single character as an ASCII value (integer).
Console.Write("Enter a character: ");
int iAsciiValue = Console.Read();
char ch = (char)iAsciiValue;
Console.WriteLine("You entered: " + ch);
Console.WriteLine("ASCII value: " + iAsciiValue);
Reading and Converting Input
Using Parse Methods
// Reading an integer
Console.Write("Enter your age: ");
int iAge = int.Parse(Console.ReadLine());
// Reading a double
Console.Write("Enter price: ");
double dPrice = double.Parse(Console.ReadLine());
// Reading a decimal
Console.Write("Enter salary: ");
decimal mSalary = decimal.Parse(Console.ReadLine());
// Reading a character
Console.Write("Enter grade (A-F): ");
char cGrade = char.Parse(Console.ReadLine());
Using Convert Class
Console.Write("Enter a number: ");
int iNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter temperature: ");
double dTemp = Convert.ToDouble(Console.ReadLine());
Formatting Output
String Concatenation
string sName = "Alice";
int iAge = 25;
Console.WriteLine("Name: " + sName + ", Age: " + iAge);
String.Format()
string sName = "Bob";
int iAge = 30;
double dScore = 85.75;
string sOutput = String.Format("Name: {0}, Age: {1}, Score: {2}",
sName, iAge, dScore);
Console.WriteLine(sOutput);
// With formatting
string sFormatted = String.Format("Score: {0:0.00}", dScore);
Console.WriteLine(sFormatted); // Score: 85.75
String Interpolation (Modern Way)
string sName = "Charlie";
int iAge = 28;
Console.WriteLine($"Name: {sName}, Age: {iAge}");
double dPrice = 19.99;
Console.WriteLine($"Price: R{dPrice:0.00}");
Number Formatting with ToString()
double dValue = 123.456789;
// Fixed decimal places
Console.WriteLine(dValue.ToString("0.00")); // 123.46
Console.WriteLine(dValue.ToString("0.0")); // 123.5
Console.WriteLine(dValue.ToString("F2")); // 123.46
Console.WriteLine(dValue.ToString("F4")); // 123.4560
// Currency
decimal mMoney = 1234.56m;
Console.WriteLine(mMoney.ToString("C")); // R1,234.56
// Integer with leading zeros
int iNumber = 7;
Console.WriteLine(iNumber.ToString("00")); // 07
Console.WriteLine(iNumber.ToString("000")); // 007
Practical Examples from Course
Example 1: User Information
using System;
namespace UserInfo
{
class Program
{
static void Main(string[] args)
{
// Get input
Console.Write("Enter your name: ");
string sName = Console.ReadLine();
Console.Write("Enter your age: ");
int iAge = int.Parse(Console.ReadLine());
Console.Write("Enter your GPA: ");
double dGPA = double.Parse(Console.ReadLine());
// Display output
Console.WriteLine("\n--- Student Information ---");
Console.WriteLine("Name: " + sName);
Console.WriteLine("Age: " + iAge);
Console.WriteLine("GPA: " + dGPA.ToString("0.00"));
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 2: Stock Trading Calculator (Practical Test 2)
using System;
namespace StockTrading
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("EasyEquities: trading product of First World Trader (Pty) Ltd");
Console.WriteLine("-------------------------------------------------------------");
Console.Write("\nEnter trader's name: ");
string sName = Console.ReadLine();
Console.Write($"\nHow much did {sName} pay for the stock (1000 shares)? R");
decimal mPurchaseAmount = decimal.Parse(Console.ReadLine());
Console.Write($"What percentage (%) did {sName} pay his broker for the purchase? ");
double dBuyingPercentage = double.Parse(Console.ReadLine()) / 100;
Console.Write($"\nHow much did {sName} sell the stock (1000 shares) for? R");
decimal mSellAmount = decimal.Parse(Console.ReadLine());
Console.Write($"What percentage (%) did {sName} pay his broker for selling? ");
double dSellingPercentage = double.Parse(Console.ReadLine()) / 100;
// Calculate
decimal mBrokerBuyingFee = mPurchaseAmount * (decimal)dBuyingPercentage;
decimal mBrokerSellingFee = mSellAmount * (decimal)dSellingPercentage;
decimal mFinalAmount = (mSellAmount - mBrokerSellingFee) -
(mPurchaseAmount + mBrokerBuyingFee);
// Display
Console.WriteLine($"\n{sName} made {mFinalAmount.ToString("C")} after the two transactions.");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 3: Hexagon Area Calculator (Worksheet 2)
using System;
namespace HexagonArea
{
class Program
{
static void Main(string[] args)
{
Console.Write("\nEnter the length of the side: ");
double dLength = double.Parse(Console.ReadLine());
double dHexagonArea = (3 * Math.Sqrt(3) / 2) * (dLength * dLength);
Console.WriteLine("\nThe area of the hexagon is " +
dHexagonArea.ToString("F4"));
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Example 4: Distance Between Two Points (Worksheet 2)
using System;
namespace DistanceCalculator
{
class Program
{
static void Main(string[] args)
{
Console.Write("\nEnter x1: ");
double dx1 = double.Parse(Console.ReadLine());
Console.Write("Enter y1: ");
double dy1 = double.Parse(Console.ReadLine());
Console.Write("Enter x2: ");
double dx2 = double.Parse(Console.ReadLine());
Console.Write("Enter y2: ");
double dy2 = double.Parse(Console.ReadLine());
double dDistance = Math.Sqrt(Math.Pow(dx2 - dx1, 2) +
Math.Pow(dy2 - dy1, 2));
Console.WriteLine("\nThe distance between the two points is " +
dDistance.ToString("F2"));
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
Using Math Class
The Math
class provides mathematical functions:
// Square root
double dResult = Math.Sqrt(16); // 4.0
// Power
double dPower = Math.Pow(2, 3); // 8.0 (2³)
double dSquare = Math.Pow(5, 2); // 25.0 (5²)
// Absolute value
double dAbs = Math.Abs(-10); // 10.0
// Rounding
double dRound = Math.Round(3.7); // 4.0
double dRound2 = Math.Round(3.4); // 3.0
// Min and Max
int iMin = Math.Min(5, 10); // 5
int iMax = Math.Max(5, 10); // 10
// Constants
double dPi = Math.PI; // 3.14159...
Practice Exercises
Exercise 1: Personal Information
Create a program that asks for: - Name - Age - City - Favorite color
Display all information in a formatted way.
Exercise 2: Rectangle Calculator
Ask user for length and width. Calculate and display: - Area = length × width - Perimeter = 2(length + width)
Exercise 3: Temperature Display
Create a program that displays a temperature conversion table using proper formatting with tabs.
Common Mistakes to Avoid
❌ Forgetting to convert input:
string sAge = Console.ReadLine();
int iResult = sAge + 5; // WRONG! Can't add string and int
✅ Correct:
int iAge = int.Parse(Console.ReadLine());
int iResult = iAge + 5; // CORRECT
❌ Not handling special characters:
Console.WriteLine("C:\Users\file.txt"); // WRONG! \U and \f are escape sequences
✅ Correct:
Console.WriteLine("C:\\Users\\file.txt"); // CORRECT
// OR
Console.WriteLine(@"C:\Users\file.txt"); // Using verbatim string
Key Takeaways
✅ Console.WriteLine()
prints with new line
✅ Console.Write()
prints without new line
✅ Console.ReadLine()
reads user input as string
✅ Always convert string input to appropriate type
✅ Use \n
for new line, \t
for tab
✅ Use ToString()
for number formatting
✅ Console.ReadKey()
pauses program
✅ Use Math
class for mathematical operations
Next Topic: C# Operators and Expressions