New Products See All

Adventures in Science: Arduino Arithmetic Operators

How to use the various math operators and compound assignment operators in C/C++.

Favorited Favorite 0

Building on data types and literals from last week, we look at how we can add, subtract, multiply and divide literals and variables in C and C++ (specifically, in the Arduino environment).

There are six main arithmetic operators in C and C++:

  • = is the assignment operator. It does not necessarily show equality but is used to set values to variables.
  • + is for addition. You can add two numbers or values in variables together.
  • - is subtraction, and it is used to subtract one number from another.
  • * is multiplication for multiplying two numbers together.
  • \ is division. Note that when using integers, you don’t get fractions or a remainder from this operation.
  • % is the modulo operator, and it is used to get the remainder from a division operation.

If you need a fractional result from division, you can use the float data type. If you’re using literals to perform the division, make sure you add some kind of decimal to one of the numbers. For example, 19 / 5 should be 19.0 / 5.

To make writing and reading code easier, you can use compound assignment operators. These perform some math operation on a variable and then store the result back in the same variable.

a += ba = a + ba += 3
a -= ba = a - ba -= 3
a *= ba = a * ba *= 3
a /= ba = a / ba /= 3
a %= ba = a % ba %= 3
a++a = a + 1a++
a--a = a - 1a--

The Arduino Reference Guide is still a good place to see which operators the Arduino supports.

While this video is intended as a reference for beginners, what slick tricks have you used or seen with operators? Any tips for good overloading practices? Please share your thoughts in the comments below.

A whole slew of new power supplies to help bring your next project to life!

Continue reading

This post explores how to use the power control features of the Battery Babysitter to make a product with the features we expect from portable embedded electronics.

Continue reading

We present another set of concepts in the computer science series as they relate to Arduino.

Continue reading

Aren't you lucky! More RFID parts, a new add-on for the Teensy and a brand-new BeagleBone!

Continue reading