Operators

Operators in Rui allow you to perform calculations, comparisons, and logical operations. Rui supports arithmetic, comparison, and logical operators.

Arithmetic Operators

Use arithmetic operators to perform mathematical calculations:

suppose a = 10
suppose b = 3

// Addition
suppose sum = a + b        // 13

// Subtraction
suppose difference = a - b // 7

// Multiplication
suppose product = a * b    // 30

// Division
suppose quotient = a / b   // 3.333...

write("Sum: " + sum)
write("Difference: " + difference)
write("Product: " + product)
write("Quotient: " + quotient)

Comparison Operators

Comparison operators return true or false based on the comparison:

suppose x = 10
suppose y = 5

// Equal to
suppose isEqual = x == y        // false

// Not equal to
suppose notEqual = x != y       // true

// Greater than
suppose greater = x > y         // true

// Less than
suppose less = x < y            // false

// Greater than or equal to
suppose greaterEqual = x >= y   // true

// Less than or equal to
suppose lessEqual = x <= y      // false

write("x == y: " + isEqual)
write("x != y: " + notEqual)
write("x > y: " + greater)

Logical Operators

Logical operators work with boolean values:

suppose a = true
suppose b = false

// AND operator
suppose andResult = a and b     // false

// OR operator
suppose orResult = a or b       // true

// NOT operator
suppose notResult = not a       // false

write("a and b: " + andResult)
write("a or b: " + orResult)
write("not a: " + notResult)

Operator Precedence

Operators have different precedence levels. Operations with higher precedence are performed first:

  1. () (parentheses)
  2. not
  3. *, /
  4. +, -
  5. ==, !=, >, <, >=, <=
  6. and
  7. or
suppose result = 2 + 3 * 4      // 14 (multiplication first)
suppose result2 = (2 + 3) * 4   // 20 (parentheses first)

write("2 + 3 * 4 = " + result)
write("(2 + 3) * 4 = " + result2)

String Operations

You can use the + operator to concatenate strings:

suppose firstName = "John"
suppose lastName = "Doe"
suppose fullName = firstName + " " + lastName

write("Full name: " + fullName)

Example: Calculator Program

Here's a simple calculator program that demonstrates operators:

// Get two numbers
suppose num1 = 15
suppose num2 = 3

// Perform calculations
suppose sum = num1 + num2
suppose difference = num1 - num2
suppose product = num1 * num2
suppose quotient = num1 / num2

// Display results
write("Calculator Results:")
write("Numbers: " + num1 + " and " + num2)
write("Sum: " + sum)
write("Difference: " + difference)
write("Product: " + product)
write("Quotient: " + quotient)

// Comparison
write("Is " + num1 + " greater than " + num2 + "? " + (num1 > num2))

Next Steps

Now that you understand operators, learn about Conditionals to make decisions in your programs.