×

C# Crash Course

Course Home C# Introduction and Setup C# Variables and Data Types C# Console Input and Output C# Operators and Expressions C# Conditional Statements - If and Else C# Switch Statements C# While and Do-While Loops C# For Loops C# Nested Loops C# Methods - Part 1 (Basics) C# Methods - Part 2 (ref, out, and Recursion) C# Arrays C# Number Systems (Binary and Hexadecimal) C# Exception Handling (Try-Catch) C# Random Numbers C# String Methods and Manipulation C# Course Summary and Best Practices


C# Course Summary and Best Practices

📚 Complete Topic Checklist

✅ Fundamentals

  • [x] Introduction and Setup
  • [x] Variables and Data Types
  • [x] Console Input and Output
  • [x] Operators and Expressions

✅ Control Flow

  • [x] Conditional Statements (if, else, else if)
  • [x] Switch Statements
  • [x] Ternary Operator

✅ Loops

  • [x] While Loops
  • [x] Do-While Loops
  • [x] For Loops
  • [x] Nested Loops
  • [x] Break and Continue

✅ Methods

  • [x] Method Basics (void and return types)
  • [x] Parameters
  • [x] ref and out parameters
  • [x] Recursion

✅ Advanced Topics

  • [x] Arrays (1D and 2D)
  • [x] Number Systems (Binary, Hexadecimal)
  • [x] Exception Handling (Try-Catch)
  • [x] Random Numbers
  • [x] ASCII Values

🎯 Essential Coding Conventions from Your Course

1. Comment Block (CRITICAL - 3 marks penalty if missing!)

// Name: Your Full Name
// Student Number: Your Student Number
// Question Number: Question 1.1

2. Variable Naming (Hungarian Notation)

Prefix Type Example
i int int iAge = 25;
d double double dPrice = 19.99;
s string string sName = "John";
c char char cGrade = 'A';
m decimal decimal mSalary = 5000.00m;
b bool bool bIsValid = true;
f float float fTemp = 36.5f;

3. Method Naming

// Start with UPPERCASE letter
static void PrintMessage()  // ✅ Correct
static void printMessage()  // ❌ Wrong

// Use descriptive names
static double CalculateArea()    // ✅ Correct
static double Calc()             // ❌ Too short

4. Always Include Exit Prompt

Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();

5. Folder Structure for Assignments

T:\Practical_Test_1_YourStudentNumber\Question1
T:\Worksheet1_YourStudentNumber\Question1.1

🔥 Common Exam Topics

Topic 1: For Loops with Methods

// Temperature conversion table
for (double dCelsius = 40.0; dCelsius >= 0.0; dCelsius--)
{
    double dFahrenheit = CelsiusToFahrenheit(dCelsius);
    Console.WriteLine($"{dCelsius:0.0}°C = {dFahrenheit:0.0}°F");
}

static double CelsiusToFahrenheit(double dCelsius)
{
    return (9.0 / 5) * dCelsius + 32;
}

Topic 2: Input Validation with Do-While

double dValue;
do
{
    Console.Write("Enter a number (1-100): ");

    if (!double.TryParse(Console.ReadLine(), out dValue))
    {
        Console.WriteLine("Invalid input");
        dValue = 101;  // Force loop to continue
    }
    else if (dValue < 1 || dValue > 100)
    {
        Console.WriteLine("Number must be between 1 and 100");
    }
} while (dValue < 1 || dValue > 100);

Topic 3: Nested Loops for Patterns

// Increasing pattern
char ch = 'A';
for (int i = 1; i <= 5; i++)
{
    for (int j = 1; j <= i; j++)
    {
        Console.Write(ch + " ");
    }
    Console.WriteLine();
    ch++;
}

Topic 4: Binary to Hexadecimal

// Read 12-bit binary, convert to hex
Console.Write("Enter 12-bit binary: ");

// Read 4 bits at a time
int i1 = Console.Read() - 48;
int i2 = Console.Read() - 48;
int i3 = Console.Read() - 48;
int i4 = Console.Read() - 48;

// Convert to decimal
int iHex = i1 * 8 + i2 * 4 + i3 * 2 + i4;

// Convert to hex character
char chHex;
if (iHex >= 10)
{
    switch (iHex)
    {
        case 10: chHex = 'A'; break;
        case 11: chHex = 'B'; break;
        case 12: chHex = 'C'; break;
        case 13: chHex = 'D'; break;
        case 14: chHex = 'E'; break;
        case 15: chHex = 'F'; break;
    }
}
else
{
    chHex = (char)(iHex + '0');
}

Topic 5: Methods with ref and out

static void UpdateStatistics(int iNum, ref int iCount, ref int iSum, out double dAverage)
{
    iCount++;              // Update using ref
    iSum += iNum;          // Update using ref
    dAverage = (double)iSum / iCount;  // Return using out
}

Topic 6: Recursion

// Even/Odd check
static bool IsEven(int iNumber)
{
    if (iNumber == 0)
        return true;
    else if (iNumber < 0)
        return false;
    else
        return IsEven(iNumber - 2);
}

// Division
static int Quotient(int iA, int iB)
{
    if (iA < iB)
        return 0;
    else
        return 1 + Quotient(iA - iB, iB);
}

⚠️ Top 10 Mistakes to Avoid

1. Missing Comment Block

// ❌ WRONG - No comment block (lose 3 marks!)

// ✅ CORRECT
// Name: John Doe
// Student Number: 12345678
// Question Number: Question 1.1

2. Wrong Variable Naming

int age = 25;        // ❌ WRONG
int iAge = 25;       // ✅ CORRECT

3. Using = Instead of ==

if (iAge = 18)       // ❌ WRONG - Assignment
if (iAge == 18)      // ✅ CORRECT - Comparison

4. Forgetting break in Switch

switch (iDay)
{
    case 1:
        Console.WriteLine("Monday");
        // ❌ Missing break!
    case 2:
        Console.WriteLine("Tuesday");
        break;  // ✅ Correct
}

5. Off-by-One Errors in Loops

for (int i = 0; i <= arr.Length; i++)  // ❌ WRONG - Goes too far
for (int i = 0; i < arr.Length; i++)   // ✅ CORRECT

6. Creating Random in Loop

// ❌ WRONG
for (int i = 0; i < 10; i++)
{
    Random rnd = new Random();
    int iNum = rnd.Next(1, 10);
}

// ✅ CORRECT
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
    int iNum = rnd.Next(1, 10);
}

7. Forgetting Return Statement

static int GetSum(int iA, int iB)
{
    int iSum = iA + iB;
    // ❌ Missing return!
}

static int GetSum(int iA, int iB)
{
    int iSum = iA + iB;
    return iSum;  // ✅ Correct
}

8. Missing ref/out in Method Call

static void Change(ref int iX)
{
    iX = 10;
}

int iNum = 5;
Change(iNum);      // ❌ WRONG - Missing ref
Change(ref iNum);  // ✅ CORRECT

9. Integer Division When Expecting Decimal

double dAvg = iSum / iCount;           // ❌ WRONG - Integer division
double dAvg = (double)iSum / iCount;   // ✅ CORRECT - Cast to double

10. Wrong Random Range

int iDice = rnd.Next(1, 6);   // ❌ WRONG - Gives 1-5
int iDice = rnd.Next(1, 7);   // ✅ CORRECT - Gives 1-6

📝 Quick Reference Formulas

Temperature Conversion

// Celsius to Fahrenheit
dFahrenheit = (9.0 / 5) * dCelsius + 32;

// Fahrenheit to Celsius
dCelsius = (5.0 / 9) * (dFahrenheit - 32);

Mathematical Formulas

// Circle Area
dArea = Math.PI * Math.Pow(dRadius, 2);

// Cylinder Volume
dVolume = Math.PI * Math.Pow(dRadius, 2) * dHeight;

// Distance between two points
dDistance = Math.Sqrt(Math.Pow(dX2 - dX1, 2) + Math.Pow(dY2 - dY1, 2));

// Hexagon Area
dArea = (3 * Math.Sqrt(3) / 2) * Math.Pow(dSide, 2);

// Rectangle Area
dArea = dLength * dWidth;

// Rectangle Perimeter
dPerimeter = 2 * (dLength + dWidth);

Number Conversions

// Character digit to integer
int iValue = ch - '0';        // '5' becomes 5
int iValue = ch - 48;         // Same thing

// Integer to character digit
char ch = (char)(iValue + '0');   // 5 becomes '5'

// Hex letter to value
int iValue = ch - 'A' + 10;   // 'A' becomes 10

🎓 Exam Strategy Tips

Before You Start

  1. ✅ Read ALL questions first
  2. ✅ Allocate time per question based on marks
  3. ✅ Start with easiest questions
  4. ✅ Write comment block FIRST

During Coding

  1. ✅ Save frequently (Ctrl+S)
  2. ✅ Test your code often (F5)
  3. ✅ Use meaningful variable names
  4. ✅ Add comments for complex logic

Before Submission

  1. ✅ Check comment block is present
  2. ✅ Test with different inputs
  3. ✅ Verify output format matches requirements
  4. ✅ Check all naming conventions

🔑 Key Defensive Programming Techniques

1. Using TryParse

if (int.TryParse(Console.ReadLine(), out int iAge))
{
    Console.WriteLine($"Valid age: {iAge}");
}
else
{
    Console.WriteLine("Invalid input");
}

2. Using Try-Catch

try
{
    int iNumber = int.Parse(Console.ReadLine());
    Console.WriteLine($"Number: {iNumber}");
}
catch
{
    Console.WriteLine("Invalid input");
}

3. Validating Ranges

if (iAge >= 0 && iAge <= 120)
{
    Console.WriteLine("Valid age");
}
else
{
    Console.WriteLine("Age must be between 0 and 120");
}

4. Checking for Division by Zero

if (iDivisor != 0)
{
    int iResult = iDividend / iDivisor;
}
else
{
    Console.WriteLine("Cannot divide by zero");
}

5. Array Bounds Checking

if (iIndex >= 0 && iIndex < iArray.Length)
{
    Console.WriteLine(iArray[iIndex]);
}
else
{
    Console.WriteLine("Index out of range");
}

📊 Data Type Reference

Integer Types

byte b = 255;              // 0 to 255
short s = 32767;           // -32,768 to 32,767
int i = 2147483647;        // -2.1 billion to 2.1 billion
long l = 9223372036854775807L;  // Very large numbers

Floating Point Types

float f = 3.14f;           // 6-7 digits precision, needs 'f'
double d = 3.14159265359;  // 15-16 digits precision
decimal m = 99.99m;        // 28-29 digits, needs 'm', for money

Other Types

char c = 'A';              // Single character
string s = "Hello";        // Text
bool b = true;             // true or false

🛠️ Useful Code Snippets

Console Output Formatting

// Two decimal places
Console.WriteLine($"{dValue:0.00}");

// Four decimal places
Console.WriteLine($"{dValue:0.0000}");

// Currency format
Console.WriteLine($"{mMoney:C}");

// Fixed format
Console.WriteLine($"{dValue:F2}");

String Formatting

// Concatenation
string sMsg = "Hello " + sName;

// String interpolation (preferred)
string sMsg = $"Hello {sName}, you are {iAge} years old";

// String.Format
string sMsg = String.Format("Hello {0}, you are {1}", sName, iAge);

Array Operations

// Find maximum
int iMax = iArray[0];
for (int i = 1; i < iArray.Length; i++)
{
    if (iArray[i] > iMax)
        iMax = iArray[i];
}

// Find minimum
int iMin = iArray[0];
for (int i = 1; i < iArray.Length; i++)
{
    if (iArray[i] < iMin)
        iMin = iArray[i];
}

// Calculate sum
int iSum = 0;
foreach (int iNum in iArray)
{
    iSum += iNum;
}

// Calculate average
double dAverage = (double)iSum / iArray.Length;

🎯 Practice Problems by Topic

Beginner Level

  1. Calculate area of rectangle (input: length, width)
  2. Convert Celsius to Fahrenheit
  3. Check if number is even or odd
  4. Print numbers 1 to 10 using a loop
  5. Create a simple calculator (+, -, *, /)

Intermediate Level

  1. Print multiplication table for a number
  2. Find factorial using recursion
  3. Validate user age (0-120) with do-while
  4. Print triangle pattern with nested loops
  5. Convert binary to hexadecimal (4 bits)

Advanced Level

  1. Generate random statistics (even/odd percentages)
  2. Implement number category checker (deficient/perfect/abundant)
  3. Create ticket pricing system with discounts
  4. Build monster battle game with random elements
  5. Sort array and find median

💡 Tips for Success

Time Management

  • 5 marks question: ~6 minutes
  • 10 marks question: ~12 minutes
  • 20 marks question: ~24 minutes
  • Reserve 10 minutes at end for testing

Debugging Tips

  1. Use Console.WriteLine() to check variable values
  2. Test with simple inputs first
  3. Check loop conditions carefully
  4. Verify array indices
  5. Test edge cases (0, negative numbers, etc.)

Common Error Messages

"Index was outside the bounds of the array"
 Check array index (must be 0 to Length-1)

"Input string was not in a correct format"
 Use TryParse for validation

"Cannot implicitly convert type 'double' to 'int'"
 Use explicit casting: (int)dValue

"Use of unassigned local variable"
 Initialize variable before use

📖 Study Checklist Before Exam

Week Before

  • [ ] Review all practical test memorandums
  • [ ] Practice each pattern from nested loops
  • [ ] Memorize temperature conversion formulas
  • [ ] Practice binary/hex conversions
  • [ ] Review method signatures (ref, out)

Day Before

  • [ ] Review naming conventions
  • [ ] Practice ASCII conversions (char to int)
  • [ ] Review Random class usage
  • [ ] Practice do-while validation patterns
  • [ ] Review recursive examples

Day Of Exam

  • [ ] Remember comment block format
  • [ ] Bring student card
  • [ ] Arrive 10 minutes early
  • [ ] Have water bottle ready
  • [ ] Stay calm and focused

🎉 Final Words

Remember These Core Principles:

  1. Always include comment block - Critical!
  2. Follow naming conventions - Hungarian notation
  3. Test your code frequently - Press F5 often
  4. Save your work - Ctrl+S is your friend
  5. Read the question carefully - Understand requirements
  6. Check output format - Match the example exactly

Most Tested Topics:

  1. ⭐⭐⭐ For loops with methods
  2. ⭐⭐⭐ Input validation with do-while
  3. ⭐⭐⭐ Nested loops (patterns)
  4. ⭐⭐ Switch statements
  5. ⭐⭐ Number system conversions
  6. ⭐⭐ Methods with ref/out
  7. ⭐⭐ Recursion
  8. ⭐ Random numbers
  9. ⭐ Exception handling

Success Formula:

Practice + Understanding + Following Conventions = Distinction

Good luck with your exams! 🍀


📚 Complete Course Navigation

  1. C# Introduction and Setup
  2. C# Variables and Data Types
  3. C# Console Input and Output
  4. C# Operators and Expressions
  5. C# Conditional Statements - If and Else
  6. C# Switch Statements
  7. C# While and Do-While Loops
  8. C# For Loops
  9. C# Nested Loops
  10. C# Methods - Part 1 (Basics)
  11. C# Methods - Part 2 (ref, out, and Recursion)
  12. C# Arrays
  13. C# Number Systems (Binary and Hexadecimal)
  14. C# Exception Handling (Try-Catch)
  15. C# Random Numbers
  16. C# Course Summary and Best Practices ← You are here

End of C# Crash Course 🎓