Menu
CoddyTech

Arithmetic Operators

Part of the First Circuits section of Coddy's Arduino journey. Lesson 14 of 22.

C++ has five arithmetic operators:

  • + adds and - subtracts
  • * multiplies
  • / divides
  • % gives the remainder of a division: 17 % 5 is 2, because 17 is three 5s with 2 left over

They work on numbers and on variables. As in school maths, *, / and % go before + and -, and parentheses go first of all:

int a = 2 + 3 * 4;    // 14: the 3 * 4 first
int b = (2 + 3) * 4;  // 20: the parentheses first

With two whole numbers, / gives a whole number: 20 / 6 is 3. The next lesson explains why.

challenge icon

Challenge

Easy

The starter has int a = 20; and int b = 6;. In setup(), print each of these on its own line, in this order:

  • a + b
  • a - b
  • a * b
  • a / b
  • a % b
  • (a + b) * 2

A label before an answer on the same line, like a + b = , is fine. Press Run, then Check.

Try it yourself

int a = 20;
int b = 6;

void setup() {
  Serial.begin(9600);
  // print the six answers, one per line
}

void loop() {
}
quiz iconTest yourself

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

All lessons in First Circuits

Practice on your own: Arduino playground