You are on page 1of 34

© Christian Jacob

Chapter 8 Arithmetic in C++
8.1 8.2 The C++ Vocabulary Variables and Types
8.2.1 8.2.2 8.2.3 Data Objects Variables Declaration of Variables

8.3

Elementary C++ Data Types
8.3.1 8.3.2 8.3.3 8.3.4 Integers Floating Point Numbers Type Conversions in Expressions Qualifiers for Variable Declarations

Chapter Overview

© Christian Jacob

8.4

Arithmetic Expressions
8.4.1 8.4.2 8.4.3 Standard Arithmetic Operators Assignments and Compound Assignments Operator Priorities

8.5

Symbolic Constants
8.5.1 8.5.2 Declaration of Symbolic Constants Hexadecimal and Octal Constants

8.6 8.7

The char Data Type References

Chapter Overview

Page 3

Chapter 8: Arithmetic in C++

© Christian Jacob

8.1

The C++ Vocabulary
asm auto bool break case catch char class const do double dynamic_cast else enum explicit export extern false float for friend if inline int long
reinterpret_cast

try
typedef typeid typename union unsigned using virtual void volatile wchar_t while

return short signed sizeof static static_cast struct switch template this throw true

main
mutable namespace new operator private protected public register

const_cast continue default

delete

goto

types — type qualifiers — execution control structures

First

Back

TOC

Prev Next

Last

..2 Variables and Types 8.) contains a value (= constant) refers to a variable.1 Data Objects The operational model of computing / programming considers a programs as a sequence of instructions for manipulating data objects. Data objects can be distinguished by their reference levels: 0 1 2 3 4 First Constant Variable Level-1 pointer Level-2 pointer … Back TOC an actual value (a number.Page 4 Chapter 8: Arithmetic in C++ © Christian Jacob 8. points to a variable refers to a level-1 pointer … Prev Next Last . a character..2.

14159 internal object internal representation Variable: Name A data objects has … • a name • an internal object reference (address) internal representation “lvalue” “rvalue” (determined by its data type) First Back TOC Prev Next Last .Page 5 Chapter 8: Arithmetic in C++ © Christian Jacob Constant: Const_Name Example: 3.

.2 Variables Variables are data objects with the following properties: • Identifier.Defined in its declaration (example: int size = 12) • Type . • Lifespan: .Its interpretation depends on its type.Dynamically defined by the program structure (see: functions). First Back TOC Prev Next Last .Page 6 Chapter 8: Arithmetic in C++ © Christian Jacob 8.2. name .Defined in its declaration (example: int size = 12) • Internal object = address of the manipulable memory section (lvalue) • Value = alterable contents of the addressed memory section .Its value can be changed by assignments (=) or specific operators (++).

3 Declaration of Variables basic_variable_declaration ::= type {name.Page 7 Chapter 8: Arithmetic in C++ © Christian Jacob 8.}*name. // true or false int number_of_items. // width and height Initializing Variables basic_variable_declaration ::= type {name_init. // number of items float width. // older C style syntax First Back TOC Prev Next Last .2. height. name_init ::= { name | name ( init ) | name = init } int counter(0). bool correct_input.}*name_init. // C++ initialization int counter = 0.

unsigned short int unsigned_short_int.Page 8 Chapter 8: Arithmetic in C++ © Christian Jacob 8. First Back TOC Elementary C++ Data Types Prev Next Last . long int long_integer. • Characters char single_character. double double_float. • Floating Point Numbers float normal_float.3 Elementary C++ Data Types • Integers int normal_integer. short int short_integer. long double high_precision_float.

648 to 2.3.483. Range of values 32 bit = 4 bytes (UNIX.Page 9 Chapter 8: Arithmetic in C++ © Christian Jacob 8.1 Integers Integers (= whole numbers) have no fractional part or decimal point.767 Types of Integers • int: • long int: • short int: • unsigned: the most efficient size for the machine is chosen (2 or 4 bytes) extra storage for integer (4 bytes guaranteed) reduced storage (2 bytes) uses all bits for the number (for 1 byte: range 0 to 65.647 -215 to 215-1 -32.147.535) Elementary C++ Data Types Prev Next Last First Back TOC .147. Mac) 16 bit = 2 bytes (PC DOS) -231 to 231-1 -2.483.768 to 32.

O´Reilly.3. • 3.2e34 ( = 1.1 1. 1997.5 • 1.2 Floating Point Numbers Floating point numbers have a decimal point or mantissa and exponent specification. First Back TOC Elementary C++ Data Types Prev Next Last .2 * 1034) Range of values The range of floating point numbers (which are always signed) and their accuracy varies widely among different computer and operating systems.Page 10 Chapter 8: Arithmetic in C++ © Christian Jacob 8. Qualline. Chapter 19.1419 • 0. Practical C++ Programming. For further details consult: S.

Page 11 Chapter 8: Arithmetic in C++ © Christian Jacob Types of Floats • float: • double: • long double: normal precision (usually 4 bytes = 32 bits) twice the range and precision of float (usually 8 bytes = 64 bits) extended precision (at least 8 bytes) First Back TOC Elementary C++ Data Types Prev Next Last .

double float This diagram is a simplified version of all possible type conversions. long int int char short int First Back TOC Elementary C++ Data Types Prev Next Last .4) contains perands of different types.3.Page 12 Chapter 8: Arithmetic in C++ © Christian Jacob 8. an automatic type conversion (to the type which is highest in the following hierarchy) is performed.3 Type Conversions in Expressions If an expression (see chapter 8.

5 % 2.Page 13 Chapter 8: Arithmetic in C++ © Christian Jacob Examples of binary operators and implicit type conversions Operator + * / % Meaning Addition Subtraction Multiplication Division Modulus.2 ⇒ 1.2 ⇒ type error First Back TOC Elementary C++ Data Types Prev Next Last .5 + 2. or remainder Integer example 5+2⇒7 5 -2 ⇒ 3 5 * 2 ⇒ 10 5/2⇒2 5%2⇒1 Floating-point example 5.5 .1 5.2 ⇒ 7.5 * 2.7 5.2 ⇒ 12.2 ⇒ 3.375 5.5 / 2.2.3 5.

7 5.8 6.Page 14 Chapter 8: Arithmetic in C++ © Christian Jacob Operator + * / % Meaning Addition Subtraction Multiplication Division Modulus.0 4 * 2.2 ⇒ 3.2 ⇒ 8.0 5.2 ⇒ 7.0 ⇒ type error First Back TOC Elementary C++ Data Types Prev Next Last .0 % 2.0 . or remainder Integer / floating-point example 5 + 2.0 / 2 ⇒ 3.

O´Reilly.}*name_init. First Back TOC Elementary C++ Data Types Prev Next Last . Practical C++ Programming. Qualline.Page 15 Chapter 8: Arithmetic in C++ © Christian Jacob 8. 76.4 Qualifiers for Variable Declarations 1 variable_declaration ::= [ special ] [ class ] [ size ] [ sign ] type {name_init. p.3. 1997. S. Special volatile <blank> Class register static extern auto <blank> Size short long <blank> Sign signed unsigned <blank> Type int float double (bool) 1.

short: .volatile: .<blank>: frequently used variable.long: .<blank>: special variable whose value may change at any time normal variable Class: .<blank>: First Back TOC larger than normal integer or very large float smaller than normal integer normal size number (integer or float) Elementary C++ Data Types Prev Next Last .extern: . kept in a machine register meaning depends on context defined in another file variable allocated from the stack auto default class is selected Size: .auto: .register: .Page 16 Chapter 8: Arithmetic in C++ © Christian Jacob Special: .static: .

float: .unsigned: signed integer or character use all integer or character bits (no sign bit) Type: .int: .char: . true or false First Back TOC Elementary C++ Data Types Prev Next Last . also used for very short integer Boolean value.Page 17 Chapter 8: Arithmetic in C++ © Christian Jacob Sign: .bool: integer floating point number double-size float single character.double: .signed: .

. simple value number constant string constant character constant identifier (declared) ..4 Arithmetic Expressions expression simple value function call unary expression binary expression . First Back TOC Arithmetic Expressions Prev Next Last ..Page 18 Chapter 8: Arithmetic in C++ © Christian Jacob 8..

Page 19 Chapter 8: Arithmetic in C++ © Christian Jacob unary expression unary operator simple value expression binary expression simple value binary operator simple value expression expression First Back TOC Arithmetic Expressions Prev Next Last .

.. binary operator + - * / % << >> = .Page 20 Chapter 8: Arithmetic in C++ © Christian Jacob unary operator + - ++ -- ... For assignments the simple value must be an identifier! First Back TOC Arithmetic Expressions Prev Next Last .

1 Standard Arithmetic Operators Arithmetics op int ⇒ int float ⇒ int float +. <. <=.Page 21 Chapter 8: Arithmetic in C++ © Christian Jacob 8. +. <=. / op float ⇒ int op int float op float ⇒ Comparisons int op int ⇒ int float ==.4. *. !=. *. >= ==. >. /. % + . <. -. >= float op float ⇒ First Back TOC Arithmetic Expressions Prev Next Last . -. >. +. !=.

<< (left shift) op int x ~x 1 0 0 1 0 1 1 0 1 0 1 0 0 1 0 1 x x << 2 1 0 0 1 0 1 1 1 1 0 1 0 0 1 0 0 First Back TOC Arithmetic Expressions Prev Next Last . ^ (xor). || (or) op int Bitwise Logical Operators op int int ⇒ int ⇒ int ~ (not) & (and). | (or).Page 22 Chapter 8: Arithmetic in C++ © Christian Jacob Logical Operators op int int ⇒ int ⇒ int ! (not) && (and). >> (right shift).

// Output: 2 First Back TOC Arithmetic Expressions Prev Next Last .Page 23 Chapter 8: Arithmetic in C++ © Christian Jacob The ? Operator condition ? true_expression : false_expression Example: int x = 15. cout << (x < 7 ? 4 : 2).

.. // loop body } First Back TOC Arithmetic Expressions Prev Next Last . expression2 Evaluates expression1 and then expression2. j=9... and finally returns the value of expression2 as the result. y = 1. . More useful in loops (see later): for (i=1. cout << (x = x + y.Page 24 Chapter 8: Arithmetic in C++ © Christian Jacob The Comma Operator: Concatenation of Two Expressions expression1 . j = j-3) { . y = y * 2).. i = i+2. Example: int x = 0.

. z. float kilos = pounds / 2.2 Assignments and Compound Assignments Syntax Diagram for Assignments assignment type identifier = expression .4. int pounds = 0. First Back TOC Arithmetic Expressions Prev Next Last .f(4)).2.. y. x = -y * (z++ .Page 25 Chapter 8: Arithmetic in C++ © Christian Jacob 8. int f(int n). . int x.

This works for the following operators in C++ : +=. <<=. |= First Back TOC Arithmetic Expressions Prev Next Last . and then store the result in the same variable. >>=. ^=. the following assignment doubles the value of j: j = j * 2. %=.Page 26 Chapter 8: Arithmetic in C++ © Christian Jacob Compound Assignments A common operation in programming is to apply an operator to a variable. *=. -=. &=. For example. /*. This can be rewritten as: j *= 2.

then increment or ++k. equivalent to k = k -1. // increment. then return value of k This also works for the decrement operator ‘--’: k--. one can write k++. // or --k. // return value of k. Instead of writing k = k + 1.Page 27 Chapter 8: Arithmetic in C++ © Christian Jacob Special Case: Increments and Decrements by One For increasing or decreasing a variable value by 1. First Back TOC Arithmetic Expressions Prev Next Last . there is even a shorter notation in C++.

b = 3. // a = 1 // a = 2. n = a++ * --b. c = 2 a = 5. // a = 6. n = 9 a = 5. // a = 6. b = 2 // a = 3. c = a++. n = 24 n = a++ * b++. b = 2. n = 15 a = 5. b = 2. n = ++a + b--. b = 3.Page 28 Chapter 8: Arithmetic in C++ © Christian Jacob Examples: a = 1. // a = 6. // a = 6. b = 4. n = 10 First Back TOC Arithmetic Expressions Prev Next Last . b = 4. b = 3. b = ++a. n = ++a * ++b.

⇐ ⇒ ⇒ ⇒ ⇒ ⇒ ⇒ ⇒ ⇒ ⇒ ⇒ ⇐ ⇐ ⇒ Associativity right to left left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right right to left right to left left to right First Back TOC Arithmetic Expressions Prev Next Last .Page 29 Chapter 8: Arithmetic in C++ © Christian Jacob 8.+ * / % + << >> < <= > >= == != & ^ | && || ?: = += -= *= /= %= &= ^= |= <<= >>= low .4.3 Operator Priorities Priority high ! ~ ++ -. Operators Ass.

1 Declaration of Symbolic Constants constant_declaration ::= const type {name_init. const float PI = 3.5 Symbolic Constants 8.Page 30 Chapter 8: Arithmetic in C++ © Christian Jacob 8.}*name_init.5.1415926. // magic Pi The values of constants can not be changed by further assignments: PI = 3.0 // Doesn’t work! First Back TOC Symbolic Constants Prev Next Last .

2 Hexadecimal and Octal Constants The C++ language has conventions for representing octal and hexadecimal values: • Octal number: leading zeros • Hexadecimal number: leading “0x” (zero + ‘x’): Examples: Base 10 6 9 15 Base 8 06 011 017 Base 16 0x6 0x9 0xF First Back TOC Symbolic Constants Prev Next Last .Page 31 Chapter 8: Arithmetic in C++ © Christian Jacob 8.5.

‘!’. lookOutChar = ‘!’. char char char char capitalA = ‘A’. newline = ‘\n’. signalling that a special character follows. ‘\b’). quote = ‘\’’ doubleQuote = ‘\”’ First Back TOC The char Data Type Prev Next Last .Page 32 Chapter 8: Arithmetic in C++ © Christian Jacob 8. smallB = ‘b’.6 The char Data Type The type char represents a single character. backslash = ‘\\’. cout << capitalB. enclosed in single quotation marks (‘A’. The backslash character (\) is called the escape character. ‘a’. char char char char char backspace = ‘\b’. capitalB = 66.

Page 33 Chapter 8: Arithmetic in C++ © Christian Jacob A small selection of special characters: Character \b \f \n \r \t \ \ \nnn \NN Name Backspace Form feed New line Return Tab Single quote Double quote Meaning Move the cursor one character to the left Go to the top of a new page Go to the next line Go to the beginning of the current line Advance to the next tab stop The character ‘ The character “ The character with The ASCII character with number nnn ASCII code nnn (octal) The character with The ASCII character with number NN (hexadecimal) ASCII code NN First Back TOC The char Data Type Prev Next Last .

Barnes. The Universal Machine. MA: WCB/ McGraw-Hill.7 References • G. 1998. Blank and R.Page 34 Chapter 8: Arithmetic in C++ © Christian Jacob 8. Chapter 3.2. First Back TOC References Prev Next Last . Boston.