1.3.10 Arithmetic Operators and Expressions

Arithmetic Expressions Produce Numeric Values

C# can combine numeric values with arithmetic operators.

Common operators include:

Plain text
+   addition
-   subtraction
*   multiplication
/   division
%   remainder

A simple soccer score update can be written as:

C#
team1.score = team1.score + 1;

The right side is an expression.

C# evaluates the expression, then assigns the result back to the field.

Read the Right Side Before the Assignment

For:

C#
team1.score = team1.score + 1;

read:

  1. get the current team1.score;
  2. add 1;
  3. assign the result to team1.score.

If the score begins at 2, the new state becomes 3.

Multiplication and Division Have Higher Precedence than Addition and Subtraction

Consider:

C#
team1.points = 2 + 3 * 4;

The multiplication is evaluated before the addition.

The result is:

Plain text
2 + 12 = 14

Parentheses can make the intended grouping explicit:

C#
team1.points = (2 + 3) * 4;

Now the result is:

Plain text
5 * 4 = 20

Types Still Matter

An expression involving int values behaves according to integer arithmetic.

A calculation that needs fractional results may require a compatible numeric type.

Detailed numeric conversion appears later in PC1.

For now, use expressions whose operand types fit the current fields.

% Produces the Remainder

For:

Plain text
7 % 2

the result is:

Plain text
1

because dividing 7 by 2 leaves a remainder of 1.

This operator becomes useful in later logic and repetition examples.

Arithmetic Is Still State Change When Assigned to a Field

The expression calculates a value.

The assignment changes the object's state.

Keep the two parts visible:

Plain text
expression → produces value
assignment → stores value

That distinction helps when predicting what the program will do.