Chapter 2
Chapter 2
Chapter 2
Introduction to C++ Programming, Input,
Output, and Operators
Objectives
• To write simple computer programs using C++
• To write simple input and output statements
• To use fundamental variable types
• Basic computer memory concepts
• To use arithmetic operators
• The precedence of arithmetic operators
• To write simple decision-making statements
3
Memory Concepts
• Variable names such as number1, number2 and sum actually
correspond to locations in the computer’s memory
• Every variable has a name, a type, a size and a value
• When a value is placed in a memory location, the value overwrites the
previous value in that location; thus, placing a new value into a memory
location is said to be destructive
34
35
Arithmetic
• Most programs perform arithmetic calculations
• The asterisk (*) indicates multiplication
• The percent sign (%) is the modulus operator:
▫ C++ provides the modulus operator, %, that yields the remainder after integer division
▫ The modulus operator can be used only with integer operands
• Integer division (i.e., where both the numerator and the denominator are
integers) yields an integer quotient
▫ Any fractional part in integer division is discarded (i.e., truncated)—no rounding occurs
36
37
Arithmetic
• Arithmetic expressions in C++ must be entered into the computer in
straight-line form
• Expressions such as “a divided by b” must be written as a/b, so that all
constants, variables and operators appear in a straight line
• Parentheses are used in C++ expressions in the same manner as in
algebraic expressions
• For example, to multiply a times the quantity b + c we write a*(b+c)
38
Arithmetic
• C++ applies the operators in arithmetic expressions in a precise
sequence determined by the following rules of operator precedence,
which are generally the same as those followed in algebra:
39
40
Arithmetic
• There is no arithmetic operator for exponentiation in C++, so x2 is
represented as x*x
• The following example illustrates the order in which the operators in a
second-degree polynomial are applied
• As in algebra, it’s acceptable to place unnecessary parentheses in an
expression to make the expression clearer
41
42