DMarlon Studio

Lesson 3 · 3 of 20

Arithmetic and casts · C

Do maths in C: addition, subtraction, multiplication, integer division, the remainder with %, casts to double and int, and the += and ++ shortcuts.

C · Arithmetic and casts in DMarlon Studio: the example's code and its output in the terminal

The +, -, * and / operators work as in maths, with one important exception: when both numbers are int, integer division drops the decimals. That is why 7 / 3 gives 2, not 2.33. The `%` operator gives the remainder of that division: 7 % 3 is 1, the pizza left over.

To keep the decimals, at least one of the numbers must be a double. You get that with a cast: (double)pizzas turns 7 into 7.0, and then the division gives 2.333333.

Order matters: in (double)(pizzas / people) the integer division happens first and gives 2; converting it afterwards cannot bring the decimals back, so you only get 2.000000.

The opposite cast, (int)bill, cuts off the decimals without rounding: 47.85 becomes 47. For the cents, the program multiplies by 100, adds 0.5 to round and keeps the last two digits with % 100.

Finally, the shortcuts: score += 5 means score = score + 5, score *= 2 means score = score * 2 and score++ adds 1. So 10 becomes 15, then 30, and ends at 31.

Code · main.c

#include <stdio.h>int main(void) {    int pizzas = 7, people = 3;    // + - * / work as in maths...    printf("Slices: %d\n", pizzas * 8);    // ...but int / int drops the decimals.    printf("Pizzas each: %d\n", pizzas / people);    // % gives the remainder of the division.    printf("Pizzas left over: %d\n", pizzas % people);    // With a double in the division, the decimals stay.    double share = (double)pizzas / people;    printf("Exact share: %f\n", share);    // Careful: the cast must come before the division.    double too_late = (double)(pizzas / people);    printf("Cast too late: %f\n", too_late);    // Turning a double into an int cuts off the decimals.    double bill = 47.85;    int euros = (int)bill;    int cents = (int)(bill * 100 + 0.5) % 100;    printf("Bill: %d euros and %d cents\n", euros, cents);    // Shortcuts that change a variable.    int score = 10;    score += 5;   // score = score + 5    score *= 2;   // score = score * 2    score++;      // add 1    printf("Score: %d\n", score);    return 0;}

Output · cc main.c -o main && ./main

Slices: 56
Pizzas each: 2
Pizzas left over: 1
Exact share: 2.333333
Cast too late: 2.000000
Bill: 47 euros and 85 cents
Score: 31

Key points

  • int / int gives a whole number: the decimals are lost.
  • % gives the remainder of integer division.
  • (double)x converts before dividing; (int)x cuts off the decimals.
  • +=, -=, *= and ++ change the variable itself.

Exercise

With 7 pizzas of 8 slices each and 5 people, work out how many slices each person gets and how many are left, using only / and %.