Understanding Basic Arithmetic

COS1511 - Introduction To Programming I · Learning C++

Understanding Basic Arithmetic

Introduction to Arithmetic Operations

In C++, basic arithmetic operations include addition, subtraction, multiplication, and division. These operations are fundamental for performing calculations and manipulating numerical data.

Arithmetic Operators

The following operators are used for basic arithmetic in C++:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulus: % (gives the remainder of a division)

Examples of Arithmetic Operations

Let us look at some examples to illustrate these operations:

Example 1: Addition

int a = 10; // First number
int b = 5;  // Second number
int sum = a + b; // Performing addition

In this example, the variable sum will hold the value 15 after executing the code.

Example 2: Subtraction

int a = 10;
int b = 5;
int difference = a - b; // Performing subtraction

The variable difference will have the value 5 after this operation.

Example 3: Multiplication

int a = 10;
int b = 5;
int product = a * b; // Performing multiplication

The variable product will be 50 after this calculation.

Example 4: Division

int a = 10;
int b = 5;
int quotient = a / b; // Performing division

The variable quotient will hold the value 2 after this operation.

Example 5: Modulus

int a = 10;
int b = 3;
int remainder = a % b; // Performing modulus

The variable remainder will be 1 since 10 divided by 3 leaves a remainder of 1.

Remember: When dividing integers in C++, the result is also an integer. For example, 5 / 2 will yield 2, not 2.5.

Order of Operations

When performing multiple arithmetic operations, the order of operations is important. The common order is:

  1. Parentheses
  2. Exponents
  3. Multiplication and Division (from left to right)
  4. Addition and Subtraction (from left to right)

In C++, you can use parentheses to change the order of operations.

Example of Order of Operations

int result = (5 + 3) * 2; // Using parentheses

In this example, result will be 16 because the addition is performed first.

Watch out: Do not forget to use parentheses when you want to ensure a specific order of operations. Failing to do so can lead to unexpected results.

Summary

  • Basic arithmetic operations include addition, subtraction, multiplication, division, and modulus.
  • Order of operations is crucial for correct calculations.
  • Use parentheses to control the order of operations.

Check your understanding

  • What is the result of 15 / 4 in C++?
  • Write a code snippet to calculate the modulus of 17 and 5.
  • Explain the order of operations in C++.
  • What will be the value of int result = 10 + 2 * 3; in C++?