3.2.3 - Arithmetic and division (C#)

3.2.3 - Arithmetic and division (C#)

Build arithmetic expressions and choose between a real quotient, an integer quotient and a remainder. Native written answers use C#. The optional runnable demonstration uses Python because C# execution is unavailable here.

Arithmetic expressions

An arithmetic expression combines numeric values to produce a result, which can be assigned to a variable or used by another expression.

C# uses + for addition, - for subtraction and * for multiplication. Multiplication and division are evaluated before addition and subtraction. Parentheses make a grouping explicit and can change the result.

C#
int adultTickets = 4;
int childTickets = 3;
int totalTickets = adultTickets + childTickets;
int seatsRemaining = 20 - totalTickets;
int totalCost = adultTickets * 8 + childTickets * 5;

The ticket count is 7, leaving 13 seats. The cost is 32 + 15 = 47. Multiplying (adultTickets + childTickets) * 8 would charge every child the adult price; correctly evaluated code can still represent the wrong rule. Translate the problem's meaning before choosing operators. 2 + 3 * 4 gives 14, while (2 + 3) * 4 gives 20.

Real division, integer division and remainders

Division can answer different questions: the exact share, the number of complete groups, or the number left over.

For 11 items divided into groups of 2, five complete groups use 10 items and one item remains. In AQA pseudocode this is 11 DIV 2 = 5 and 11 MOD 2 = 1. In C#, / performs integer division when both operands are integers; % obtains the remainder. To get real division, ensure at least one operand is real.

C#
int completeGroups = 11 / 2;
int leftOver = 11 % 2;
double exactShare = 11 / 2.0;

These values are 5, 1 and 5.5. Declaring double exactShare = 11 / 2; would store 5.0: the integer division happens before assignment, so a real destination does not restore the discarded fraction. Use 2.0 or convert an operand, for example (double)items / groupSize.

An hour contains 60 minutes. From 135 minutes, 135 / 60 gives 2 complete hours and 135 % 60 gives 15 remaining minutes. For positive whole numbers, remainder zero also tests divisibility, as in number % 2 == 0 for an even number.

Predict the three outputs below, then run the optional Python demonstration. Change items = 11 to items = 12 and rerun. Python's // explicitly performs integer division; this is a demonstration of the values, not the required C# syntax.

Optional Python demonstration: grouping items

{"code":"items = 11\nprint(items // 2)\nprint(items % 2)\nprint(items / 2)","instructions":"Predict and run. Then change items = 11 to items = 12 and predict/run again."}