Upload
mohanesh
View
240
Download
0
Embed Size (px)
Citation preview
8/14/2019 4 Operators and Expressions
1/24
4 Operators and Expressions
4.1
4.2
Operators
Arithmetic Operators4.2.1Unary Operator4.2.2Binary Operators4.2.3Increment and Decrement
Operator4.2.4Precedence of arithmetic
Operators
Relational Operators
Logical Operators
Assignment Operator
Precedence of Operators
Expressions
4.7.1Mixed Mode Expressions andCast
4.7.2Spacing and Parentheses
Sample Programs4.8.1Sample Program 14.8.2Sample Program 24.8.3Sample Program 3
Summary
Exercises
Learning Objectives
Upon successful completion of this chapter, students will be
able to:
Describe operatorsDemonstrate an understanding of arithmetic operators,
relational operators, and logical operatorUse assignment operatorDemonstrate an understanding of operator precedence
Describe the various forms of expression
4.3
4.4
4.5
4.6
4.7
4.8
4.9
4.10
8/14/2019 4 Operators and Expressions
2/24
Fundamentals to Programming
In this chapter, we will discuss the operators and expressions, and the assignment statementin C++ programming language.
4.1 Operators
A mathematician uses more than just the variables. A mathematician can add them together,
subtract them, multiply them, and perform an almost endless list of other operations.
C++ offers the same set of basic operations. C++ programs can multiply, add, divide, and so
forth. Programs have to be able to perform these operations in order to get anything done.
4C++ is very rich in built-in operators. Operator triggers some computations when applied tooperands in an expression. The commonly used operators are as follows:
Arithmetic operators
Relational operatorsLogical operator
Assignment operator
Table 4-1 shows the commonly use operators in C++ programming language.
Arithmeticoperators
+-*
/%
Table 4-1
Relationaloperators
>=
8/14/2019 4 Operators and Expressions
3/24
Operators and Expressions
Arithmetic Operator+-+-
*/
%
Table 4-2
DescriptionUnary plus
Unary minus
Addition
SubstractionMultiplication
Floating-point division (floating-point result)
Intreger division (no fraction part)Modulus (remainder from the integer division)
Arithmetics operators
The first two operators are unary operator. Unary oprarators just take one operand(argument). The remaining five are binary operators. Binary operators take two operands.
4.2.1 Unary Operator
The + and - operator can be unary or binary. A unary operator has only one operand (inother words, unary operators take a single argument) while a binary operator has twooperands. For example, the - operator in -5 can be considered as a unary operator to negatenumber 5, whereas the - operator in 4 -5 is a binary operator for subtracting 5 from 4.
You an assign a positive or negative number to a variable by using a unary + or-. For
instance,
m = +12
n = -12
// Assigns 'm' a positive 12
// Assigns 'n' a negative 12
4
Unary operators operate on a single value. Thus sizeof operator, decrement operator and
increment operator are unary operators.
Here is a program example using unary operator.
// Program that uses unary operator#include
main(){
intintintint
abcd
====
+10;-a;-b;-(-b);
====
"
8/14/2019 4 Operators and Expressions
4/24
Fundamentals to Programming
Here is the output.
abcd
====
10-a = -10-b = 10-(-b) = -10
4.2.2 Binary Operators
A binary operator is one that has two arguments. If you can say var1 op var2, op must
be a binary operator. The most common binary operators are the simple operations youperformed in grade school.
4 There are five standard arithmetic operators in C++ as shown in following table. Thearithmetic operators are use to manipulate values in programs.Operator Description+Addition
-Subtraction
*Multiplication
/Division
%Modulus
(remainder)
Table 4-3
Example25 + 2, the result is 27
25 - 2, the result is 23
25 * 2, the result is 50
25 / 2, the result is 11 for integer; 11.5 for floating point
25 % 2, the result is 1 (that is, 25 / 2 = 11 with
remainder of 1)
Binary arithmetic operators
When you divide two integers, the result will be an integer. In other words, any fractional
part of the result is lost. For example, the result of25 / 2 is 11, even though is 11.5 in amathematical expression.
When you use modulus operator with two integers, the result is an integer with the value ofthe remainder after division takes place, so the result of25 % 2 is 1.
Here are some examples of operations involving integer variables. The expressions on the left
evaluate to the values on the right. Let say
m=5n=2
Expressionm+nm-nm*nm/nm%n
Table 4-4
Result 7
3
10
2
1 Remainder is discarded
Produces remainder of division
Arithmetic operation involving integer variable
When the forward slash / is applied to integer operands, any remainder with be truncated
while the modulus (%) produces the remainder of the division.
82
8/14/2019 4 Operators and Expressions
5/24
Operators and Expressions
The modulus operator (%), increment operator (++) and decrement operator (--) only can beused with integers. You can not use with floating-point data.
Here is an example using arithmetic operators.
// Program using arithmetic operators# include
main(){
int value1 = 43, value2 = 10, sum;int difference, product, quotient, modulus;
sum = value1 + value2;difference = value1 - value2;product = value1 * value2;quotient = value1 / value2;modulus = value1 % value2;
cout
8/14/2019 4 Operators and Expressions
6/24
Fundamentals to Programming
Operator Called++Pre-increment
Expression++m
++ Post-increment m++
-- Pre-decrement --n
4 -- Post-decrement n--
Explanationm = 5, n = 2 6Increment m by 1, then thenew value of m in the
expression in which m
resides.
Use the current value of m in6
the expression in which mresides, then increment m by
1.
1Decrement n by 1, then usethe new value of n in the
expression in which n
resides.
Use the current value of n in1the expression in which n
resides, then decrement n by
1.
Table 4-5 The increment and decrement operators
For pre-increment and pre-decrement, (i.e., ++a or --a), the operation is performed and the
value is produced. For post-increment and post-decrement (i.e. a++ or a--), the value is
produced, then the operation is performed.
Here is an example using pre-increment and post-increment operator.
// Program to show pre-incrementing and post-incrementing operation
#include
main(){
int n;n = 5;cout
8/14/2019 4 Operators and Expressions
7/24
Operators and Expressions
Here is the output.
566
556
4.2.4 Precedence of arithmetic Operators
Arithmetic operators have the following precedence:
Highest Arithmetic Operator Operator
+ - ++ --UnaryOperators
Arithmetic multiply, divide, remainder (modulus) * / %
+-Arithmetic add
and subtract
4
LowestFigure 4-1 Precedence of arithmetic operators
When you combine mathematical operations in a single statement, you must understandoperator precedence, or the order in which parts of a mathematical expression are evaluated.
Multiplication, division and modulus always take place prior to addition and subtraction in an
expression. For the expression
int result = 2 + 3 * 4;
The results is 14, because the multiplication (3 * 4) occurs before adding 2. You can
override normal operator precedence by putting the operation to perform in parentheses. Theexpression
int result = (2 + 3) * 4;
results in 20, because the addition within the parentheses takes place first, and then that result(5) is multiplied by 4.
85
8/14/2019 4 Operators and Expressions
8/24
Fundamentals to Programming
4.3 Relational Operators
Relational operators are also known as comparison operators. A relational operator compares
two items. There are six relational operators in C++ as shown in the table below.
Operator===!=
Table 4-6
4
DescriptionLess Than
Greater ThanEqual to
Less than or equal to
Greater than on equal to
Not equal to
Relational operators
True Example347575
2== 7= 3!= 6
False Example823813
4== 9=2!= 3
The results of evaluation of a relational operation is either true (represented by 1) or false
(represented by 0).
When you use any of the operators that have two symbols (==, =, or !=), you cannotplace any whitespace (blank space) between the two symbols.
86
8/14/2019 4 Operators and Expressions
9/24
Operators and Expressions
Here is a sample program testing therelational operators.
// Program that testing the relational operators#include
main()
{cout
8/14/2019 4 Operators and Expressions
10/24
Fundamentals to Programming
Here is the output.
The results of evaluation of a relational operationtrue (represented by 1) or false (represented by 0).
Testing greater than
100 > 10 results in 110 > 100 results in 0100 > 100 results in 0
Testing less than10 < 100 results in 1100 < 10 results in 0100 < 100 results in 0
4Testing greater thanor equal to100 >= 10 results in 110 >= 100 results in 0100 >= 100 results in 1
Testing less than or equal to10
8/14/2019 4 Operators and Expressions
11/24
Operators and Expressions
Here is a sample program testing the logical operators.
// Program that testing the logical operators#include
main(){
// Output to screencout
8/14/2019 4 Operators and Expressions
12/24
Fundamentals to Programming
4.5 Assignment Operator
C++ has several assignment operators. The most commonly used assignment operator is =.
The assignment operator is used to change the value of a variable. Assignment operations
using = has the general form
identifier = expression;
where identifier generally represents a variable and expression represent a value, constant, a
variable or a more complex expression. Here are some examples of assignment operations.
4num_of_seat = 50;interest_rate = 0.05;char newline = '\n';area_of_rectangle = (width + height) * 2;salary = basic_pay + overtime_hours * overtime_rate;
There is a shorthand notation that combines the assignment operator (=) and an arithmeticoperator so that a given variable can have its value changed by adding, subtracting,
multiplying by, or dividing by a specified values. The general form is
identifier = arithmetic_operator (expression);
The expression can be another variable, a constant or more complicated arithmetic expression.
Below are examples:
Assignment Statementcount += 2;total -= discount;bonus *= 2;time /= rush_factor;change %= 100;amount *= count1 + count2;
Equivalent tocount = count + 2;total = total - discountbonus = bonus * 2;time = time / rush_factorchange = change % 100;amount = amount * (count1 + count 2)
90
8/14/2019 4 Operators and Expressions
13/24
Operators and Expressions
// Program that demonstrating the assignment operators#include
main(){
// Variable declaration and initializationfloat m = 0.0, n = 0.0, result = 0.0;
// Prompt for inputcoutm>>n;
// Testing the assignment (=) operatorresult = m + n;cout
8/14/2019 4 Operators and Expressions
14/24
Fundamentals to Programming
4.6 Precedence of Operators
The hierarchy of operator precedence from highest to lowest is summarized in figure below.
Highest Operator CategoryUnary OperatorsArithmetic multiply, divide, remainder
Arithmetic add and subtract
Relational operatorsLogical operators
Assignment
Precedence of operators
Operator++ -- + -*/%+-> < >= ++m * --n + 4&& p++ + q-- * 4 < x++ * y-- + 4;
cout
8/14/2019 4 Operators and Expressions
15/24
Operators and Expressions
4.7 Expressions
Expressions in C++ are formed by properly combining operators, variables and constants. As
in algebra, C++ expression can be complex. Parentheses are used to force the order of
evaluation. An expression may also contain spaces for readability. Here are some examplesof C++ expressions.
gross_pay deductions(basic_pay + hours * rate) (socso +epf)(k * k - 5 * j* h) >100(gender == 'm') && (age > 20)(size == 'M' || size = 'L') && price
8/14/2019 4 Operators and Expressions
16/24
Fundamentals to Programming
// Program to illustrate data conversion#include
main(){
int a = 5;float b = 2, c = 3.0, d;d = c + a / b;cout
8/14/2019 4 Operators and Expressions
17/24
Operators and Expressions
Here is the output.
Result = 15
4
95
8/14/2019 4 Operators and Expressions
18/24
Fundamentals to Programming
4.8 Sample Programs
4.8.1 Sample Program 1
Program 4-11 begins with a comment that explains what the program does. The body of the
main function includes a declaration section where the variables w, h, perimeter and
area are defined and initialized. It is follow by a sequence of executable statements. These
statements compute the perimeter and area. Finaly, it display results to screen.
// Program to compute perimeter and area#include
main()
{// Variable declaration and initializationfloat w = 0.0, h = 0.0, perimeter = 0.0, area = 0.0;
// Prompts for inputcoutw;couth;
// Computes the perimeterperimeter = 2 * (w + h);
// Computes the areaarea = w * h;
// Output results to screencout
8/14/2019 4 Operators and Expressions
19/24
Operators and Expressions
4.8.2 Sample Program 2
Program 3-11 begins with a comment that explains what the program does. The body of themain function includes a declaration section where the variables value1 and value2, and
are defined. It is follow by a sequence of executable statements. These statement display thecomparison results of variables value1 and value2.
// Program that comparing two numbers entered from keyboard#include
main(){
// Variable declaration and initializationfloat value1 = 0.0, value2 = 0.0;
// Input and output statements
coutvalue1;coutvalue2;
// Output result to screencout
8/14/2019 4 Operators and Expressions
20/24
Fundamentals to Programming
4.8.3 Sample Program 3
Program 4-13 computes the amount earned. The program starts with the declaration andinitialization of constant variable rate, and variable total and day. Given the number of
days worked and the daily rate, the program first converts or casts the value ofday (aninteger) to a floating-point number before using it in the multiplication. Finaly, it displays the
result to screen.
// Program to calculate the amount of money earned#include
main(){
// Constant & variable declaration and initializationconst float rate = 50.00;float total = 0.00;int day = 0;
// Prompts for inputcoutday;
// Computes the perimetertotal = (float) day * rate; // Converts day to floating point
// Output results to screencout
8/14/2019 4 Operators and Expressions
21/24
Operators and Expressions
4.9 Summary
The commonly used operators in C++ are arithmetic operators, relational operators,
logical operators, and assignment operators.
There are five standard arithmetic operators: +, -, *, /, %.
There are six comparison operators: >, =,
8/14/2019 4 Operators and Expressions
22/24
Fundamentals to Programming
4.10 Exercises
1. What is the numerical value of each of the following expressions as evaluated by the
C++ programming language?
a.
b.
c.
d.e.
f.
g.h.
i.
j.
a.
b.c.
d.
e.f.
g.
h.
i.j.
3+6*4
6/3*8
18 / 2 + 14 /2
16 % 217 % 2
28 % 5
28 % 5 * 3 + 120 / (4 +1)
(10 + 20) / 5
'B' - 'A'
27
1616
0
13
10
4
61
4
2. What is the value of each of the following expressions?
a.b.
c.
d.
e.f.
g.
h.
i.j.
a.b.
c.
d.e.
f.
g.
h.
i.
100
4>16= 42
6 == 9
2 + 5 == 78 + 3
8/14/2019 4 Operators and Expressions
23/24
Operators and Expressions
j. 0
3. Given integer variables x, y, and z with values 10, 7, and 2 respectively. Determinethe valued of each of the following arithmetic expressions.
a.b.c.
d.
e.f.
a.b.
c.
d.
e.f.
x + y - 2zx / z (x * x +y)(x * y) % z
5 * (x + y + z) x / z
x*yx*zy * (x + z) * (x y)
13535
0
90
50252
4
4. Using the values given in exercise 3, determine the values for the each af thefollowing expressions:
a.
b.c.
d.
e.
f.
a.b.
c.
d.e.
f.
x++
x < 2 && z > 5.0y >= x
z != 10
x < y || y > z
(z * 5) == x
110
0
11
1
5. The assignment operator in the C++ programming language is ____________.
a.
b.
c.d.
=
==
=>+=
6. The equal to comparison operator is ____________.
a.b.
c.
d.
===
!=
!!
101
8/14/2019 4 Operators and Expressions
24/24
Fundamentals to Programming
7. If you attempt to add a float, an int and a long, the result will be a(n) ____________.
a.b.
c.
d.
floatint
long
error message
8. Which assignment is correct?
a.
b.c.
d.
char code = 3;
char code = "three";char code = "3";
char code = '3';
49. What is the output of the following program lines?
a = 'b';b = 'c';c = a;cout