C# Programming · Lesson 4

Smooth Operators — Programming Examples

Five runnable C# examples covering operator precedence, increment/decrement and compound assignment, logical comparisons with a floating-point caution, short-circuit logic, and implicit/explicit type conversion.

  • operators
  • precedence
  • increment
  • comparison
  • short-circuit
  • type-conversion

Example 1 — Weighting Quiz Scores with Order of Operations

This example builds a weighted quiz total using the simple arithmetic operators and shows how parentheses force C# to add the scores before the multiplication that scales them, instead of letting * run first.

using System;

class Program
{
    static void Main()
    {
        int quiz1 = 82;
        int quiz2 = 90;
        int quiz3 = 76;

        // Without parentheses, * happens before +, which is NOT what we want here.
        int wrongTotal = quiz1 + quiz2 + quiz3 * 3;

        // Parentheses force C# to add the three scores first, then scale the sum.
        int correctTotal = (quiz1 + quiz2 + quiz3) * 3;

        double average = correctTotal / 3.0;

        Console.WriteLine("Wrong total (bad precedence): " + wrongTotal);
        Console.WriteLine("Correct total (parentheses):  " + correctTotal);
        Console.WriteLine("Average: " + average);

        // Modulo shows whether the total is an even or odd number of points.
        int remainder = correctTotal % 2;
        Console.WriteLine(remainder == 0 ? "Total is even." : "Total is odd.");
    }
}

Example 2 — Prefix vs. Postfix in an Attendance Counter

This example adjusts a running attendance count with the compound assignment operators, then shows the difference between the prefix (++n) and postfix (n++) increment operators.

using System;

class Program
{
    static void Main()
    {
        int attendance = 20;

        attendance += 3;   // Three more students arrive.
        attendance -= 1;   // One student leaves early.
        Console.WriteLine("Attendance after adjustments: " + attendance);

        int n = attendance;

        // Postfix: n++ returns the ORIGINAL value, then increments n.
        int postfixResult = n++;
        Console.WriteLine("postfixResult = " + postfixResult + ", n is now " + n);

        n = attendance;

        // Prefix: ++n increments n FIRST, then returns the new value.
        int prefixResult = ++n;
        Console.WriteLine("prefixResult = " + prefixResult + ", n is now " + n);
    }
}

Example 3 — Checking Pass/Fail Scores Safely

This example uses the logical comparison operators to grade a score, then shows why comparing two double values with == can silently fail due to rounding, and how Math.Abs fixes it.

using System;

class Program
{
    static void Main()
    {
        int score = 68;
        int passingScore = 70;

        bool passed = score >= passingScore;
        bool failed = score < passingScore;
        bool isPerfect = score == 100;

        Console.WriteLine("Passed: " + passed);
        Console.WriteLine("Failed: " + failed);
        Console.WriteLine("Perfect score: " + isPerfect);

        // Floating-point comparison pitfall.
        double total = 10;
        double third = total / 3;
        bool looksEqual = (3 * third) == total;                       // Often false due to rounding.
        bool actuallyEqual = Math.Abs((3 * third) - total) < 0.00001; // Reliable.

        Console.WriteLine("(3 * third) == total: " + looksEqual);
        Console.WriteLine("Close enough with Math.Abs: " + actuallyEqual);
    }
}

Example 4 — Enrollment Eligibility with && and ||

This example combines two conditions with && to check enrollment eligibility, then relies on short-circuit && to skip a division entirely when it would divide by zero.

using System;

class Program
{
    static void Main()
    {
        int age = 17;
        bool hasPrerequisite = true;

        // && requires BOTH conditions to be true.
        bool canEnroll = (age >= 16) && hasPrerequisite;
        Console.WriteLine("Can enroll: " + canEnroll);

        // || requires AT LEAST ONE condition to be true.
        bool needsAdvising = (age < 18) || !hasPrerequisite;
        Console.WriteLine("Needs advising: " + needsAdvising);

        // Short-circuit && protects the division: if seatsRemaining is 0,
        // C# never evaluates the right side, so no divide-by-zero happens.
        int studentsWaiting = 12;
        int seatsRemaining = 0;

        if (seatsRemaining != 0 && studentsWaiting / seatsRemaining > 1)
        {
            Console.WriteLine("More than one student per seat.");
        }
        else
        {
            Console.WriteLine("No seats remaining, or the ratio is fine.");
        }
    }
}

Example 5 — Implicit Promotion vs. Explicit Cast in an Average

This example shows C# implicitly promoting an int to a double to preserve a fractional average, then uses an explicit cast to deliberately truncate that average back down to a whole number.

using System;

class Program
{
    static void Main()
    {
        int totalPoints = 259;
        int assignmentCount = 4;

        // int / int truncates, losing the decimal portion.
        int truncatedAverage = totalPoints / assignmentCount;
        Console.WriteLine("Truncated average (int / int): " + truncatedAverage);

        // Dividing by 4.0 forces implicit promotion of totalPoints to double.
        double accurateAverage = totalPoints / 4.0;
        Console.WriteLine("Accurate average (int / double): " + accurateAverage);

        // Explicit cast: deliberately demote the double back to an int.
        int roundedDown = (int)accurateAverage;
        Console.WriteLine("Explicit cast back to int: " + roundedDown);

        // The following line would NOT compile without a cast:
        // int bad = accurateAverage;   // Cannot implicitly convert type 'double' to 'int'
    }
}