Free Ebook cover C# Essentials: Building Console Apps with .NET

C# Essentials: Building Console Apps with .NET

New course

12 pages

Operators and Expressions in C# Console Programs

CapĂ­tulo 4

Estimated reading time: 7 minutes

+ Exercise

Expressions as the Building Blocks of Logic

An expression is any combination of values, variables, operators, and method calls that produces a value. Console programs rely on expressions to calculate results, make decisions, and build readable output.

Examples of expressions:

  • subtotal + tax produces a numeric value.
  • age >= 18 produces a boolean (true/false).
  • (isMember && total > 50m) || hasCoupon produces a boolean used to decide a discount.

Arithmetic Operators

Arithmetic operators compute numeric results.

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % remainder (modulo)
  • + unary plus, - unary minus

Step-by-step: Compute a Total with Tax

This example calculates a subtotal, adds tax, and prints a formatted report line.

decimal price = 19.99m;     // per item price (decimal is typical for money calculations)  int quantity = 3;  decimal subtotal = price * quantity;  decimal taxRate = 0.08m;  decimal tax = subtotal * taxRate;  decimal total = subtotal + tax;  Console.WriteLine($"Subtotal: {subtotal:0.00}"); Console.WriteLine($"Tax:      {tax:0.00}"); Console.WriteLine($"Total:    {total:0.00}");

Division and Remainder

Division behaves differently depending on operand types. With integers, division truncates the fractional part. With decimal or double, you get a fractional result.

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

int a = 7; int b = 2;  int intQuotient = a / b;   // 3 (truncates) int remainder = a % b;     // 1  decimal decQuotient = 7m / 2m; // 3.5  Console.WriteLine($"7 / 2 as int = {intQuotient}, remainder = {remainder}"); Console.WriteLine($"7 / 2 as decimal = {decQuotient}");

Use % for tasks like checking even/odd or splitting items into groups.

int number = 42; bool isEven = number % 2 == 0; Console.WriteLine($"{number} is even: {isEven}");

Comparison Operators

Comparison operators produce a boolean result.

  • == equal to
  • != not equal to
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to

Step-by-step: Check a Range

Range checks are common for validating inputs and applying rules.

int score = 87;  bool isPassing = score >= 60; bool isInA = score >= 90 && score <= 100;  Console.WriteLine($"Passing: {isPassing}"); Console.WriteLine($"In A range (90-100): {isInA}");

When checking a range, combine two comparisons with a logical operator (covered next).

Logical Operators (Boolean Logic)

Logical operators combine or invert boolean expressions.

  • && AND (short-circuit): second operand evaluated only if needed
  • || OR (short-circuit): second operand evaluated only if needed
  • ! NOT: inverts a boolean
  • & AND (non-short-circuit): evaluates both sides
  • | OR (non-short-circuit): evaluates both sides

Short-circuiting in Practice

Short-circuiting helps avoid unnecessary work and can prevent errors when the second condition depends on the first.

int itemsInCart = 0; bool hasPaymentMethod = false;  bool canCheckout = itemsInCart > 0 && hasPaymentMethod; Console.WriteLine($"Can checkout: {canCheckout}");

Because itemsInCart > 0 is false, the second condition is not evaluated. This pattern is useful when the second condition might require a valid object or a non-empty value.

Combining Conditions for Business Rules

Example: apply free shipping if the order is large enough or the customer is a premium member, but not if the address is international.

decimal orderTotal = 72m; bool isPremiumMember = false; bool isInternational = true;  bool qualifiesForFreeShipping = (orderTotal >= 50m || isPremiumMember) && !isInternational; Console.WriteLine($"Free shipping: {qualifiesForFreeShipping}");

Assignment Operators

Assignment stores a value into a variable. The basic operator is =. Compound assignments combine an operation with assignment.

  • = assign
  • += add and assign
  • -= subtract and assign
  • *= multiply and assign
  • /= divide and assign
  • %= remainder and assign

Step-by-step: Accumulate a Running Total

Compound assignment is common when summing values.

decimal total = 0m;  decimal item1 = 12.50m; decimal item2 = 5.25m; decimal item3 = 3.00m;  total += item1; total += item2; total += item3;  Console.WriteLine($"Total: {total:0.00}");

Increment and Decrement

++ increases by 1 and -- decreases by 1. They can be prefix or postfix, which matters when used inside larger expressions.

int x = 5; int a = ++x; // x becomes 6, a is 6  int y = 5; int b = y++; // b is 5, y becomes 6  Console.WriteLine($"a={a}, x={x}"); Console.WriteLine($"b={b}, y={y}");

For clarity in console apps, prefer using ++/-- on their own line unless you specifically need the prefix/postfix behavior.

Operator Precedence and Parentheses

When multiple operators appear in one expression, C# evaluates them in a defined order called precedence. Parentheses () let you override precedence and make intent explicit.

A practical precedence summary (higher to lower):

  • Unary: !, unary -, ++, --
  • Multiplicative: *, /, %
  • Additive: +, -
  • Comparison: >, <, >=, <=
  • Equality: ==, !=
  • Logical AND: &&
  • Logical OR: ||
  • Assignment: =, +=, etc.

Clear Examples of Precedence

int result1 = 2 + 3 * 4;      // 14 (3*4 first) int result2 = (2 + 3) * 4;    // 20 (parentheses first)  bool expr1 = true || false && false;  // true (&& before ||) bool expr2 = (true || false) && false; // false  Console.WriteLine($"result1={result1}, result2={result2}"); Console.WriteLine($"expr1={expr1}, expr2={expr2}");

Use parentheses when combining arithmetic and boolean logic in the same statement, especially for business rules, to avoid mistakes and improve readability.

Structured Practice Tasks

Task 1: Compute Totals

Create expressions to compute a receipt total.

  • Given decimal unitPrice and int quantity, compute subtotal.
  • Given decimal taxRate, compute tax and total.
  • Print all three values with two decimal places.
decimal unitPrice = 4.75m; int quantity = 6; decimal taxRate = 0.075m;  decimal subtotal = unitPrice * quantity; decimal tax = subtotal * taxRate; decimal total = subtotal + tax;  Console.WriteLine($"Subtotal: {subtotal:0.00}"); Console.WriteLine($"Tax:      {tax:0.00}"); Console.WriteLine($"Total:    {total:0.00}");

Task 2: Apply Discounts

Compute a discount amount and final price. Use parentheses to make the formula obvious.

  • Discount rule: 15% off if isMember is true, otherwise 0%.
  • Compute discountRate, discountAmount, and finalTotal.
decimal subtotal = 120m; bool isMember = true;  decimal discountRate = isMember ? 0.15m : 0m; decimal discountAmount = subtotal * discountRate; decimal finalTotal = subtotal - discountAmount;  Console.WriteLine($"Discount rate: {discountRate:P0}"); Console.WriteLine($"Discount:      {discountAmount:0.00}"); Console.WriteLine($"Final total:   {finalTotal:0.00}");

The conditional operator ?: is a compact way to choose between two values based on a boolean expression.

Task 3: Check Ranges

Write boolean expressions for validation.

  • Check if a temperature is within a safe range: 18 to 27 inclusive.
  • Check if a quantity is between 1 and 100 inclusive.
int temperature = 29; bool safeTemp = temperature >= 18 && temperature <= 27;  int qty = 0; bool validQty = qty >= 1 && qty <= 100;  Console.WriteLine($"Safe temperature: {safeTemp}"); Console.WriteLine($"Valid quantity:   {validQty}");

Task 4: Combine Conditions

Build a rule that uses multiple comparisons and logical operators.

  • Allow a purchase if: (age is at least 18 AND has ID) OR has guardian consent.
  • Print the decision as a boolean.
int age = 17; bool hasId = false; bool hasGuardianConsent = true;  bool canPurchase = (age >= 18 && hasId) || hasGuardianConsent; Console.WriteLine($"Can purchase: {canPurchase}");

Mini-Challenge: Console Report Using Multiple Operators

Build a small console report that calculates totals, applies conditional discounts, checks eligibility rules, and prints a clear summary. Use arithmetic, comparison, logical operators, assignment operators, and parentheses.

Requirements

  • Compute subtotal from two items (price and quantity for each).
  • Apply a discount if: customer is a member AND subtotal is at least 50, OR they have a coupon.
  • Discount rate: 10% if eligible, otherwise 0%.
  • Compute tax (use 8%).
  • Compute final total.
  • Compute and print flags: discountEligible, freeShippingEligible (final total at least 75 AND not international).
  • Print a report with aligned labels.
decimal item1Price = 14.99m; int item1Qty = 2; decimal item2Price = 9.50m;  int item2Qty = 3;  bool isMember = true; bool hasCoupon = false; bool isInternational = false;  decimal subtotal = 0m; subtotal += item1Price * item1Qty; subtotal += item2Price * item2Qty;  bool discountEligible = (isMember && subtotal >= 50m) || hasCoupon; decimal discountRate = discountEligible ? 0.10m : 0m; decimal discountAmount = subtotal * discountRate;  decimal discountedSubtotal = subtotal - discountAmount;  decimal taxRate = 0.08m; decimal tax = discountedSubtotal * taxRate; decimal finalTotal = discountedSubtotal + tax;  bool freeShippingEligible = (finalTotal >= 75m) && !isInternational;  Console.WriteLine("ORDER REPORT"); Console.WriteLine($"Item 1 total:        {(item1Price * item1Qty):0.00}"); Console.WriteLine($"Item 2 total:        {(item2Price * item2Qty):0.00}"); Console.WriteLine($"Subtotal:            {subtotal:0.00}"); Console.WriteLine($"Discount eligible:   {discountEligible}"); Console.WriteLine($"Discount ({discountRate:P0}):      {discountAmount:0.00}"); Console.WriteLine($"After discount:      {discountedSubtotal:0.00}"); Console.WriteLine($"Tax ({taxRate:P0}):           {tax:0.00}"); Console.WriteLine($"Final total:         {finalTotal:0.00}"); Console.WriteLine($"International:       {isInternational}"); Console.WriteLine($"Free shipping:       {freeShippingEligible}");

Now answer the exercise about the content:

In C#, why is it recommended to use the short-circuit AND operator (&&) instead of the non-short-circuit AND operator (&) when combining boolean conditions in console app logic?

You are right! Congratulations, now go to the next page

You missed! Try again.

The && operator short-circuits: if the first condition is false, the second is not evaluated. This can improve efficiency and help avoid errors when the second check requires a valid object or value.

Next chapter

Control Flow: Conditions and Loops for Interactive Apps

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.