Cpp - Operator Arithmetic Operators

Introduction

There are five mathematical operators:

addition (+), 
subtraction (-), 
multiplication ( *), 
division  (/), and 
modulus (%). 

Integer division differs from ordinary division.

Integer division produces only integers, so the remainder is dropped.

The value returned by 21 / 4 is 5.

The modulus operator % returns the remainder value of integer division, so 21 % 4 equals 1.

Floating-point division is ordinary division. The expression 21 / 4.0 equals 5.25.

C++ decides which division to perform based on the type of the operands.

If at least one operand is a floating-point variable or literal, the division is floating point. Otherwise, it is integer division.

Compound Operators

The following expression adds 10 to the value of a variable named score:

score = score + 10; 

This can be written more simply using the += self-assigned addition operator:

score += 10; 

The self-assigned addition operator += adds the r-value to the l-value, and then assigns the result to the l-value.

There are self-assigned subtraction (-=), division (/=), multiplication ( *=), and modulus (%=) operators, as well.

Related Topics

Exercise