Menu
Coddy logo textTech

Operator Precedence

Part of the Logic & Flow section of Coddy's C# journey — lesson 38 of 66.

Operator precedence determines the order in which operators are evaluated in an expression. Understanding precedence is crucial for writing correct logical expressions.

Look at this example:

int result = 5 + 3 * 2;

What's the value of result? It's 11, not 16, because multiplication has higher precedence than addition.

Here's a simplified precedence order (from highest to lowest):

  1. Parentheses ()
  2. Multiplication/Division * / %
  3. Addition/Subtraction + -
  1. Comparison operators < > <= >=
  2. Equality operators == !=
  1. Logical AND &&
  2. Logical OR ||
  3. Assignment operators = += -= etc.

Let's see how this applies:

bool result = 5 > 3 && 10 < 20 || 7 == 8;

First, the comparisons are evaluated: 5 > 3 is true, 10 < 20 is true, and 7 == 8 is false.
Then, logical AND: true && true is true.
Finally, logical OR: true || false is true.

So result is true.

Use parentheses to make your code clearer:

bool result = (5 > 3 && 10 < 20) || (7 == 8);
challenge icon

Challenge

Easy

Create a method named EvaluateExpression that takes three integers (a, b, c) and returns a boolean.

Your method should return the result of this expression:
a > b || a == c && b < c

Then, create another method named EvaluateWithParentheses that evaluates:
(a > b || a == c) && b < c

Your program should read three integers from the console and print the results of both evaluations on separate lines.

Try it yourself

using System;

class Program
{
    public static bool EvaluateExpression(int a, int b, int c)
    {
        // Write your code here
    }
    
    public static bool EvaluateWithParentheses(int a, int b, int c)
    {
        // Write your code here
    }
    
    static void Main(string[] args)
    {
        Console.WriteLine("Enter three integers:");
        int a = int.Parse(Console.ReadLine());
        int b = int.Parse(Console.ReadLine());
        int c = int.Parse(Console.ReadLine());
        
        // Call your methods and print the results
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow