×

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# Conditional Statements - If and Else

What are Conditional Statements?

Conditional statements allow your program to make decisions and execute different code based on conditions.

if (condition)
{
    // Code executes if condition is true
}

The if Statement

Basic Syntax

if (condition)
{
    // Code to execute if condition is true
}

Example

int iAge = 20;

if (iAge >= 18)
{
    Console.WriteLine("You are an adult");
}

Single Line (Without Braces)

if (iAge >= 18)
    Console.WriteLine("You are an adult");  // Only this line executes

// Multiple statements need braces
if (iAge >= 18)
{
    Console.WriteLine("You are an adult");
    Console.WriteLine("You can vote");
}

The if-else Statement

Execute one block if condition is true, another if false.

Syntax

if (condition)
{
    // Code if condition is true
}
else
{
    // Code if condition is false
}

Example

int iNumber = 10;

if (iNumber % 2 == 0)
{
    Console.WriteLine("Even number");
}
else
{
    Console.WriteLine("Odd number");
}

The else-if Statement

Test multiple conditions in sequence.

Syntax

if (condition1)
{
    // Code if condition1 is true
}
else if (condition2)
{
    // Code if condition2 is true
}
else if (condition3)
{
    // Code if condition3 is true
}
else
{
    // Code if all conditions are false
}

Example: Grade Classification

int iMarks = 75;

if (iMarks >= 80)
{
    Console.WriteLine("Distinction");
}
else if (iMarks >= 70)
{
    Console.WriteLine("First Class");
}
else if (iMarks >= 60)
{
    Console.WriteLine("Second Class");
}
else if (iMarks >= 50)
{
    Console.WriteLine("Pass");
}
else
{
    Console.WriteLine("Fail");
}

Nested if Statements

An if statement inside another if statement.

int iAge = 25;
bool hasLicense = true;

if (iAge >= 18)
{
    if (hasLicense)
    {
        Console.WriteLine("You can drive");
    }
    else
    {
        Console.WriteLine("You need a license");
    }
}
else
{
    Console.WriteLine("You are too young to drive");
}

Practical Examples from Course

Example 1: Coordinate Quadrant Checker (Practical Test 3)

using System;

namespace QuadrantChecker
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Input the value of X coordinate: ");
            int iCoorX = int.Parse(Console.ReadLine());

            Console.Write("Input the value of Y coordinate: ");
            int iCoorY = int.Parse(Console.ReadLine());

            string sMsg = "\nThe coordinate point ";

            if (iCoorX > 0 && iCoorY > 0)
            {
                sMsg += $"({iCoorX}, {iCoorY}) lies in the First quadrant.";
            }
            else if (iCoorX < 0 && iCoorY > 0)
            {
                sMsg += $"({iCoorX}, {iCoorY}) lies in the Second quadrant.";
            }
            else if (iCoorX < 0 && iCoorY < 0)
            {
                sMsg += $"({iCoorX}, {iCoorY}) lies in the Third quadrant.";
            }
            else if (iCoorX > 0 && iCoorY < 0)
            {
                sMsg += $"({iCoorX}, {iCoorY}) lies in the Fourth quadrant.";
            }
            else if (iCoorX == 0 && iCoorY == 0)
            {
                sMsg += $"({iCoorX}, {iCoorY}) lies at the origin.";
            }
            else if (iCoorX == 0 && iCoorY > 0)
            {
                sMsg += $"({iCoorX}, {iCoorY}) lies on the positive Y axis.";
            }
            else if (iCoorX == 0 && iCoorY < 0)
            {
                sMsg += $"({iCoorX}, {iCoorY}) lies on the negative Y axis.";
            }
            else if (iCoorY == 0 && iCoorX > 0)
            {
                sMsg += $"({iCoorX}, {iCoorY}) lies on the positive X axis.";
            }
            else if (iCoorY == 0 && iCoorX < 0)
            {
                sMsg += $"({iCoorX}, {iCoorY}) lies on the negative X axis.";
            }

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

Example 2: Circle Overlap Checker (Worksheet 3)

using System;

namespace CircleOverlap
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("\nEnter Circle 1's center x-coordinate: ");
            double dXCoorCircle1 = double.Parse(Console.ReadLine());

            Console.Write("Enter Circle 1's center y-coordinate: ");
            double dYCoorCircle1 = double.Parse(Console.ReadLine());

            Console.Write("Enter Circle 1's radius: ");
            double dRadiusCircle1 = double.Parse(Console.ReadLine());

            Console.Write("\nEnter Circle 2's center x-coordinate: ");
            double dXCoorCircle2 = double.Parse(Console.ReadLine());

            Console.Write("Enter Circle 2's center y-coordinate: ");
            double dYCoorCircle2 = double.Parse(Console.ReadLine());

            Console.Write("Enter Circle 2's radius: ");
            double dRadiusCircle2 = double.Parse(Console.ReadLine());

            // Calculate distance between centers
            double dDistanceCentres = Math.Sqrt(
                Math.Pow(dXCoorCircle2 - dXCoorCircle1, 2) + 
                Math.Pow(dYCoorCircle2 - dYCoorCircle1, 2)
            );

            string sMsg = "\nConclusion: ";

            if (dDistanceCentres <= (dRadiusCircle1 - dRadiusCircle2))
            {
                sMsg += "Circle 2 is inside Circle 1";
            }
            else if (dDistanceCentres <= dRadiusCircle1 + dRadiusCircle2)
            {
                sMsg += "Circle 2 overlaps Circle 1";
            }
            else
            {
                sMsg += "Circle 2 does not overlap Circle 1";
            }

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

Example 3: Loan Eligibility Checker (Worksheet 5)

using System;

namespace LoanEligibility
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the Loan Eligibility Checker!");

            Console.Write("Enter your monthly income (R): ");
            decimal mMonthlyIncome = decimal.Parse(Console.ReadLine());

            Console.Write("Enter your credit score (300-850): ");
            int iCreditScore = int.Parse(Console.ReadLine());

            Console.Write("Are you employed? (Y/N): ");
            char cEmployed = char.Parse(Console.ReadLine().ToUpper());

            bool isEmployed = (cEmployed == 'Y');

            Console.WriteLine("\n--- Eligibility Result ---");
            Console.WriteLine($"Monthly Income: R{mMonthlyIncome:0.00}");
            Console.WriteLine($"Credit Score: {iCreditScore}");
            Console.WriteLine($"Employment Status: {(isEmployed ? "Employed" : "Not Employed")}");

            // Check eligibility
            if (isEmployed && mMonthlyIncome >= 2000 && iCreditScore >= 600)
            {
                Console.WriteLine("Result: Congratulations! You are eligible for a loan.");
            }
            else
            {
                Console.WriteLine("Result: Sorry, you are not eligible for a loan.");
                Console.WriteLine("Reasons for ineligibility:");

                if (!isEmployed)
                {
                    Console.WriteLine("- You must be employed to qualify.");
                }
                if (mMonthlyIncome < 2000)
                {
                    Console.WriteLine("- Monthly income must be at least R2000.");
                }
                if (iCreditScore < 600)
                {
                    Console.WriteLine("- Credit score must be at least 600.");
                }
            }

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

Example 4: Movie Ticket Pricing (Practical Test 5)

using System;

namespace MovieTicket
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Movie Theater Ticket Price Calculator");

            Console.Write("Enter your age: ");
            int iAge = int.Parse(Console.ReadLine());

            Console.Write("\nIs the showtime (A)fternoon or (E)vening? Enter A or E: ");
            string sShowtime = Console.ReadLine().ToUpper();

            decimal mBasePrice;
            string sShowtimeType;
            string sTicketType;

            // Determine base price
            if (sShowtime == "A")
            {
                mBasePrice = 8.00m;
                sShowtimeType = "Afternoon";
            }
            else
            {
                mBasePrice = 12.00m;
                sShowtimeType = "Evening";
            }

            // Calculate discount
            decimal mPrice;
            if (iAge <= 12)
            {
                mPrice = mBasePrice * 0.60m;  // 40% discount
                sTicketType = "Child";
            }
            else if (iAge >= 65)
            {
                mPrice = mBasePrice * 0.75m;  // 25% discount
                sTicketType = "Senior";
            }
            else
            {
                mPrice = mBasePrice;
                sTicketType = "Adult";
            }

            // Display result
            Console.WriteLine("\nTicket Details:");
            Console.WriteLine($"Age: {iAge}");
            Console.WriteLine($"Showtime: {sShowtimeType}");
            Console.WriteLine($"Ticket Type: {sTicketType}");
            Console.WriteLine($"Price: R{mPrice:0.00}");

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

Ternary Operator (Shorthand if-else)

A shorthand way to write simple if-else statements.

Syntax

variable = (condition) ? expressionTrue : expressionFalse;

Examples

// Instead of:
int iAge = 20;
string sStatus;
if (iAge >= 18)
{
    sStatus = "Adult";
}
else
{
    sStatus = "Minor";
}

// You can write:
string sStatus = (iAge >= 18) ? "Adult" : "Minor";

// More examples
int iNumber = 10;
string sType = (iNumber % 2 == 0) ? "Even" : "Odd";

int iA = 5, iB = 10;
int iMax = (iA > iB) ? iA : iB;

bool isEmployed = true;
string sEmploymentStatus = isEmployed ? "Employed" : "Not Employed";

Common Patterns

Checking Range

int iMarks = 75;

// Check if marks are in valid range
if (iMarks >= 0 && iMarks <= 100)
{
    Console.WriteLine("Valid marks");
}
else
{
    Console.WriteLine("Invalid marks");
}

Multiple Conditions with AND

int iAge = 25;
decimal mIncome = 3000;
bool hasID = true;

if (iAge >= 18 && mIncome >= 2000 && hasID)
{
    Console.WriteLine("Eligible");
}

Multiple Conditions with OR

char cGrade = 'B';

if (cGrade == 'A' || cGrade == 'B' || cGrade == 'C')
{
    Console.WriteLine("Pass");
}
else
{
    Console.WriteLine("Fail");
}

Practice Exercises

Exercise 1: Age Category

Write a program that classifies age: - 0-12: Child - 13-19: Teenager - 20-59: Adult - 60+: Senior

Exercise 2: Temperature Advice

Get temperature from user: - Below 0: "Freezing" - 0-15: "Cold" - 16-25: "Comfortable" - Above 25: "Hot"

Exercise 3: Login System

Get username and password: - If both correct: "Login successful" - If username wrong: "Invalid username" - If password wrong: "Invalid password"

Common Mistakes to Avoid

Using = instead of ==:

if (iAge = 18)  // WRONG! Assignment, not comparison

Correct:

if (iAge == 18)  // CORRECT!

Semicolon after if:

if (iAge >= 18);  // WRONG! Semicolon ends the if
{
    Console.WriteLine("Adult");  // Always executes
}

Correct:

if (iAge >= 18)
{
    Console.WriteLine("Adult");
}

Missing braces for multiple statements:

if (iAge >= 18)
    Console.WriteLine("Adult");
    Console.WriteLine("Can vote");  // Always executes!

Correct:

if (iAge >= 18)
{
    Console.WriteLine("Adult");
    Console.WriteLine("Can vote");
}

Key Takeaways

✅ Use if to execute code conditionally ✅ Use else for alternative execution ✅ Use else if to test multiple conditions ✅ Always use == for comparison, not = ✅ Use && when all conditions must be true ✅ Use || when at least one condition must be true ✅ Use braces {} for clarity and multiple statements ✅ Ternary operator is shorthand for simple if-else


Next Topic: C# Switch Statements