×

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# Operators and Expressions

Arithmetic Operators

Arithmetic operators perform mathematical operations.

Operator Name Description Example Result
+ Addition Adds two values 5 + 3 8
- Subtraction Subtracts one value from another 5 - 3 2
* Multiplication Multiplies two values 5 * 3 15
/ Division Divides one value by another 10 / 2 5
% Modulus Returns division remainder 10 % 3 1
++ Increment Increases value by 1 x++ x = x + 1
-- Decrement Decreases value by 1 x-- x = x - 1

Basic Examples

int iA = 10;
int iB = 3;

int iSum = iA + iB;           // 13
int iDifference = iA - iB;    // 7
int iProduct = iA * iB;       // 30
int iQuotient = iA / iB;      // 3
int iRemainder = iA % iB;     // 1

Console.WriteLine("Sum: " + iSum);
Console.WriteLine("Difference: " + iDifference);
Console.WriteLine("Product: " + iProduct);
Console.WriteLine("Quotient: " + iQuotient);
Console.WriteLine("Remainder: " + iRemainder);

Division: Integer vs. Decimal

// Integer division (truncates decimal)
int iResult1 = 10 / 3;        // 3 (not 3.333...)
int iResult2 = 7 / 2;         // 3 (not 3.5)

// Decimal division
double dResult1 = 10.0 / 3;   // 3.333...
double dResult2 = 10 / 3.0;   // 3.333...
double dResult3 = (double)10 / 3;  // 3.333... (casting)

Console.WriteLine(iResult1);   // 3
Console.WriteLine(dResult1);   // 3.333333...

Increment and Decrement

// Post-increment (use then increase)
int iX = 5;
int iY = iX++;    // iY = 5, iX = 6
Console.WriteLine("X: " + iX + ", Y: " + iY);  // X: 6, Y: 5

// Pre-increment (increase then use)
int iA = 5;
int iB = ++iA;    // iB = 6, iA = 6
Console.WriteLine("A: " + iA + ", B: " + iB);  // A: 6, B: 6

// Post-decrement
int iM = 10;
int iN = iM--;    // iN = 10, iM = 9

// Pre-decrement
int iP = 10;
int iQ = --iP;    // iQ = 9, iP = 9

Modulus Operator (%)

The modulus operator returns the remainder of division.

// Check if number is even or odd
int iNumber = 10;
if (iNumber % 2 == 0)
{
    Console.WriteLine("Even");
}
else
{
    Console.WriteLine("Odd");
}

// More examples
int iRem1 = 10 % 3;   // 1
int iRem2 = 15 % 4;   // 3
int iRem3 = 20 % 5;   // 0
int iRem4 = 7 % 2;    // 1

Assignment Operators

Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3

Examples

int iX = 10;

iX += 5;    // iX = 15 (same as iX = iX + 5)
iX -= 3;    // iX = 12 (same as iX = iX - 3)
iX *= 2;    // iX = 24 (same as iX = iX * 2)
iX /= 4;    // iX = 6  (same as iX = iX / 4)
iX %= 4;    // iX = 2  (same as iX = iX % 4)

// Common pattern in loops
int iSum = 0;
iSum += 10;   // Add 10 to sum
iSum += 20;   // Add 20 to sum
Console.WriteLine(iSum);  // 30

Comparison Operators

Comparison operators return a boolean value (true or false).

Operator Name Example Returns
== Equal to x == y true if x equals y
!= Not equal x != y true if x does not equal y
> Greater than x > y true if x is greater than y
< Less than x < y true if x is less than y
>= Greater than or equal x >= y true if x ≥ y
<= Less than or equal x <= y true if x ≤ y

Examples

int iA = 10;
int iB = 5;

bool isEqual = (iA == iB);           // false
bool isNotEqual = (iA != iB);        // true
bool isGreater = (iA > iB);          // true
bool isLess = (iA < iB);             // false
bool isGreaterOrEqual = (iA >= 10);  // true
bool isLessOrEqual = (iB <= 5);      // true

Console.WriteLine("A == B: " + isEqual);
Console.WriteLine("A > B: " + isGreater);

Logical Operators

Logical operators are used to combine conditional statements.

Operator Name Description Example
&& Logical AND Returns true if both statements are true x < 5 && x < 10
|| Logical OR Returns true if one statement is true x < 5 || x < 4
! Logical NOT Reverses the result !(x < 5 && x < 10)

AND Operator (&&)

Both conditions must be true.

int iAge = 25;
bool hasLicense = true;

// Both conditions must be true
if (iAge >= 18 && hasLicense)
{
    Console.WriteLine("You can drive");
}

// Example from loan eligibility
decimal mIncome = 3000;
int iCreditScore = 650;
bool isEmployed = true;

if (isEmployed && mIncome >= 2000 && iCreditScore >= 600)
{
    Console.WriteLine("Eligible for loan");
}

OR Operator (||)

At least one condition must be true.

int iDay = 6;

if (iDay == 6 || iDay == 7)
{
    Console.WriteLine("It's the weekend!");
}

char cGrade = 'A';
if (cGrade == 'A' || cGrade == 'B')
{
    Console.WriteLine("Excellent work!");
}

NOT Operator (!)

Reverses the boolean value.

bool isRaining = false;

if (!isRaining)
{
    Console.WriteLine("It's not raining");
}

bool isValid = true;
if (!isValid)
{
    Console.WriteLine("Invalid");
}
else
{
    Console.WriteLine("Valid");  // This will execute
}

Combining Logical Operators

int iAge = 20;
bool hasTicket = true;
bool hasID = true;

// Complex condition
if ((iAge >= 18 && hasID) && hasTicket)
{
    Console.WriteLine("Entry allowed");
}

// Multiple OR conditions
char cOperator = '+';
if (cOperator == '+' || cOperator == '-' || 
    cOperator == '*' || cOperator == '/')
{
    Console.WriteLine("Valid operator");
}

Operator Precedence

Operators are evaluated in a specific order:

  1. Parentheses ()
  2. Increment/Decrement ++, --
  3. Multiplication/Division/Modulus *, /, %
  4. Addition/Subtraction +, -
  5. Comparison <, >, <=, >=
  6. Equality ==, !=
  7. Logical AND &&
  8. Logical OR ||
  9. Assignment =, +=, -=, etc.

Examples

// Without parentheses
int iResult1 = 2 + 3 * 4;      // 14 (not 20)
// 3 * 4 is evaluated first = 12, then 2 + 12 = 14

// With parentheses
int iResult2 = (2 + 3) * 4;    // 20
// (2 + 3) is evaluated first = 5, then 5 * 4 = 20

// Complex expression
int iResult3 = 10 + 5 * 2 / 2 - 3;  // 12
// Step 1: 5 * 2 = 10
// Step 2: 10 / 2 = 5
// Step 3: 10 + 5 = 15
// Step 4: 15 - 3 = 12

// With parentheses for clarity
int iResult4 = (10 + 5) * (2 / 2) - 3;  // 12

Practical Examples from Course

Example 1: Calculator (From Worksheet 2)

using System;

namespace SimpleCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter first number: ");
            double dNum1 = double.Parse(Console.ReadLine());

            Console.Write("Enter second number: ");
            double dNum2 = double.Parse(Console.ReadLine());

            Console.Write("Enter operator (+, -, *, /): ");
            char cOperator = char.Parse(Console.ReadLine());

            double dResult = 0;

            if (cOperator == '+')
            {
                dResult = dNum1 + dNum2;
            }
            else if (cOperator == '-')
            {
                dResult = dNum1 - dNum2;
            }
            else if (cOperator == '*')
            {
                dResult = dNum1 * dNum2;
            }
            else if (cOperator == '/')
            {
                if (dNum2 != 0)
                {
                    dResult = dNum1 / dNum2;
                }
                else
                {
                    Console.WriteLine("Error: Cannot divide by zero");
                    return;
                }
            }

            Console.WriteLine($"\nResult: {dNum1} {cOperator} {dNum2} = {dResult}");

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

Example 2: Temperature Conversion (From Practical Test 1)

// Celsius to Fahrenheit: (9.0 / 5) * Celsius + 32
double dCelsius = 40.0;
double dFahrenheit = (9.0 / 5) * dCelsius + 32;
Console.WriteLine($"{dCelsius}°C = {dFahrenheit}°F");

// Fahrenheit to Celsius: (5.0 / 9) * (Fahrenheit - 32)
double dFahr = 120.0;
double dCels = (5.0 / 9) * (dFahr - 32);
Console.WriteLine($"{dFahr}°F = {dCels}°C");

Example 3: Even/Odd Checker

using System;

namespace EvenOddChecker
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a number: ");
            int iNumber = int.Parse(Console.ReadLine());

            if (iNumber % 2 == 0)
            {
                Console.WriteLine($"{iNumber} is even");
            }
            else
            {
                Console.WriteLine($"{iNumber} is odd");
            }

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

Practice Exercises

Exercise 1: BMI Calculator

Calculate BMI = weight / (height * height) - Get weight (kg) and height (m) from user - Calculate and display BMI

Exercise 2: Grade Calculator

  • Get marks from user
  • Calculate percentage
  • Determine if pass (≥50%) or fail (<50%)

Exercise 3: Discount Calculator

  • Get original price
  • If price > R1000, apply 10% discount
  • Otherwise, apply 5% discount
  • Display final price

Common Mistakes to Avoid

Using = instead of == in comparisons:

if (x = 5)  // WRONG! This is assignment
{
    Console.WriteLine("x is 5");
}

Correct:

if (x == 5)  // CORRECT! This is comparison
{
    Console.WriteLine("x is 5");
}

Integer division when expecting decimal:

double dResult = 10 / 3;  // 3.0 (not 3.333...)

Correct:

double dResult = 10.0 / 3;  // 3.333...
// OR
double dResult = (double)10 / 3;

Incorrect operator precedence:

int iResult = 10 + 5 * 2;  // 20, not 30!

Use parentheses for clarity:

int iResult = (10 + 5) * 2;  // 30

Key Takeaways

✅ Arithmetic operators: +, -, *, /, % ✅ Use % to find remainder (useful for even/odd checks) ✅ Comparison operators return boolean values ✅ && requires all conditions to be true ✅ || requires at least one condition to be true ✅ ! reverses a boolean value ✅ Use parentheses to control operator precedence ✅ Be careful with integer vs. decimal division


Next Topic: C# Conditional Statements (if, else, switch)