Professional Documents
Culture Documents
4.7 Expressions
4.7.1Mixed Mode Expressions and
Cast
4.7.2Spacing and Parentheses
4.9 Summary
4.10 Exercises
Fundamentals to Programming
In this chapter, we will discuss the operators and expressions, and the assignment statement
in 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.
C++ is very rich in built-in operators. Operator triggers some computations when applied to
4
operands in an expression. The commonly used operators are as follows:
§ Arithmetic operators
§ Relational operators
§ Logical operator
§ Assignment operator
Table 4-1 shows the commonly use operators in C++ programming language.
Expressions are made up of constants, variables, and operator. The following are all valid
arithmetic expressions:
beta + 4
rate – 1.5
2- price
price * discount
m*x+c
The operators allowed in an expression depend on the data types of the constants and
variables. Table 4-2 shows the arithmetics operators used in C++ programming language.
80
Operators and Expressions
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.
Unary operators operate on a single value. Thus sizeof operator, decrement operator and
increment operator are unary operators.
main()
{
int a = +10;
int b = -a;
int c = -b;
int d = -(-b);
cout<<"a = "<<a<<endl;
cout<<"b = -a = "<<b<<endl;
cout<<"c = -b = "<<c<<endl;
cout<<"d = -(-b) = "<<d<<endl;
}
Program 4-1 Program that uses unary operator
81
Fundamentals to Programming
a = 10
b = -a = -10
c = -b = 10
d = -(-b) = -10
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 you
performed in grade school.
4 There are five standard arithmetic operators in C++ as shown in following table. The
arithmetic operators are use to manipulate values in programs.
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 of 25 / 2 is 11, even though is 11.5 in a
mathematical expression.
When you use modulus operator with two integers, the result is an integer with the value of
the remainder after division takes place, so the result of 25 % 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=5
n=2
Expression Result
m+n 7
m-n 3
m*n
10
m/n
m%n 2
1 ← Remainder is discarded
Table 4-4 ← 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
Operators and Expressions
The modulus operator (%), increment operator (++) and decrement operator (--) only can be
used with integers. You can not use with floating-point data.
main()
{
int value1 = 43, value2 = 10, sum;
int difference, product, quotient, modulus;
Sum is 53
Difference is 33
Product is 430
Quotient is 4
Modulus is 3
In C++, the increment operator is ++ and means “increase by one unit.” The decrement
operator is -- and means “decrease by one unit.”
There are two versions of each type of operator, often called the prefix and postfix versions
which is summarized in the table 5-3. Pre-increment means the ++ operator appears before
the variable or expression, and post-increment means the ++ operator appears after the
variable or expression.
Similarly, pre-decrement means the -- operator appears before the variable or expression,
and post-decrement means the -- operator appears after the variable or expression.
83
Fundamentals to Programming
4
the expression in which n
-- Post-decrement n-- resides, then decrement n by
1.
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.
main()
{
int n; // Declare varible n
n = 5; // Set n equal to 5
cout<<n<<endl; // Display n
cout<<++n<<endl; // Add 1 to n then Display n
cout<<n<<endl; // Display n
cout<<n<<endl; // Display n
cout<<n++<<endl; // Display n then add 1 to n
cout<<n<<endl; // Diaplay n
return 0;
}
Program 4-3 Program to show pre-incrementing and post-incrementing operation
84
Operators and Expressions
5
6
6
5
5
6
When you combine mathematical operations in a single statement, you must understand
operator 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. The
expression
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
Fundamentals to Programming
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.
4
Relational operators
When you use any of the operators that have two symbols (==, <=, >=, or !=), you cannot
place any whitespace (blank space) between the two symbols.
86
Operators and Expressions
main()
{
cout<<"The results of evaluation of a relational operation"<<endl;
cout<<"true (represented by 1) or false (represented by 0)."<<endl;
cout<<endl; // An empty line
// Testing equal to
cout<<"\nTesting equal to"<<endl;
cout<<"100 == 100 results in "<<(100 == 100)<<endl;
cout<<"100 == 10 results in "<<(100 == 10)<<endl;
cout<<"10 == 100 results in "<<(10 == 100)<<endl;
return 0;
}
Program 4-4 Program that testing the relational operators
87
Fundamentals to Programming
4
100 >= 10 results in 1
10 >= 100 results in 0
100 >= 100 results in 1
Testing equal to
100 == 100 results in 1
100 == 10 results in 0
10 == 100 results in 0
In addition to use simple relational expressions, we can create more complex expressions by
using the logical operations AND, OR and NOT.
The three logical operators in C++ are represented by the symbols as shown in the Table 4-7
below.
Operator Description
&& AND
|| OR
! NOT
Table 4-7
Logical operators
M n m && n m || n !m
Both m and n must be Either m or n must be Produces the opposite
true true relation
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
Table 4-8 Logical operations on m and n
88
Operators and Expressions
main()
{
// Output to screen
cout<<"true = 1, false = 0"<<endl;
return 0;
}
Program 4-5 Program that testing the logical operators
true = 1, false = 0
89
Fundamentals to Programming
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.
num_of_seat = 50;
interest_rate = 0.05;
There is a shorthand notation that combines the assignment operator (=) and an arithmetic
operator 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
The expression can be another variable, a constant or more complicated arithmetic expression.
Below are examples:
90
Operators and Expressions
main()
{
// Variable declaration and initialization
float m = 0.0, n = 0.0, result = 0.0;
return 0;
}
Program 4-6 Program that testing the assignment operators
Enter 2 numbers: 5 2
5+2 = 7
5-2 = 3
5*2 = 10
5/2 = 2.5
91
Fundamentals to Programming
The hierarchy of operator precedence from highest to lowest is summarized in figure below.
Lowest
4
Figure 4-2 Precedence of operators
Here is a sample program testing the operator precedence from highest to lowest.
main()
{
int result = 0;
int a = 2, b = 3;
int m = 2, n = 3;
int p = 2, q = 3;
int x = 2, y = 3;
cout<<"\nResult = "<<result;
return 0;
}
Program 4-7 Program that testing the precedence of operators
Result = 0
92
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 examples
of 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 <= 20
main()
{
int a = 5, b = 2;// both a and b are type int
float c = 3.0, d;
d = c + a / b;
cout<<"Result = "<<d;
return 0;
}
Program 4-8Program to illustrate data conversion
Result = 5
The expression a / b is evaluated to 2 since both a and b are of type int and no data
convertion takes place (the fraction part .5 is dropped. Next, since c is of type float
(require more bytes), the result is then added to the value in c (3.0). The end result 5.0 is
finally stored in d.
However if a or b is declared as type float, then a / b would evaluate to 2.5 in which case d
would have the value 5.5 as shown in following program.
93
Fundamentals to Programming
main()
{
int a = 5;
float b = 2, c = 3.0, d; // c and d is now declare as float
d = c + a / b;
cout<<"Result = "<<d;
return 0;
}
Program 4-9 Program to illustrate data conversion
4 Result = 5.5
The function cast may be used to force an expression to be of a specific data type. It has the
general forms
(type)expression
expression(type)
With reference to the statement d = c + a / b;, any of the following six expressions can be
used to preserve the fractional part of a / b.
c + (float)a / b;
c + float (a) / b;
c + a / (float)b;
c + a / float (b);
c + (float)a / (float)b;
c + float(a) / float(b);
You may place space in an expression or a statement to make it more readable. Use of or
additional or redundant parentheses will not cause errors or slow down the execution of an
expression. It is shows in Program 4-10 below.
main()
{
{
{
{
cout<<"Result = ";
cout<<((((1 + 2) + 3) + 4) + 5);
}
}
}
}
Program 4-10 Program to test the spacing and parentheses
94
Operators and Expressions
Result = 15
95
Fundamentals to Programming
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.
4
#include <iostream.h>
main()
{
// Variable declaration and initialization
float w = 0.0, h = 0.0, perimeter = 0.0, area = 0.0;
return 0;
}
Program 4-11 Program to compute perimeter and area
96
Operators and Expressions
Program 3-11 begins with a comment that explains what the program does. The body of the
main 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 the
comparison results of variables value1 and value2.
main()
{
// Variable declaration and initialization
float value1 = 0.0, value2 = 0.0;
return 0;
}
Program 4-12 Program that comparing two numbers entered from keyboard
True = 1, false = 0
2.3 > 9.8 results in 0
2.3 < 9.8 results in 1
2.3 >= 9.8 results in 0
2.3 <= 9.8 results in 1
2.3 == 9.8 results in 0
97
Fundamentals to Programming
Program 4-13 computes the amount earned. The program starts with the declaration and
initialization 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 of day (an
integer) to a floating-point number before using it in the multiplication. Finaly, it displays the
result to screen.
main()
{
4
// Constant & variable declaration and initialization
const float rate = 50.00;
float total = 0.00;
int day = 0;
return 0;
}
Program 4-13 Program to calculate the amount of money earned
For 10 days of work with the daily rate $ 50, you have earned $ 500.
98
Operators and Expressions
4.9 Summary
§ The commonly used operators in C++ are arithmetic operators, relational operators,
logical operators, and assignment operators.
§ There are six comparison operators: >, <, >=, <=, ==, !=.
99
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. 3+6*4
b. 6/3*8
c. 18 / 2 + 14 /2
d. 16 % 2
e. 17 % 2
f. 28 % 5
g. 28 % 5 * 3 + 1
h. 20 / (4 +1)
4
i. (10 + 20) / 5
j. 'B' - 'A'
a. 27
b. 16
c. 16
d. 0
e. 1
f. 3
g. 10
h. 4
i. 6
j. 1
a. 4>1
b. 6<= 18
c. 42 >= 42
d. 6 == 9
e. 2 + 5 == 7
f. 8 + 3 <= 10
g. 3 != 9
h. 13 != 13
i. -4 != 4
j. 2 + 5 * 3 == 21
a. 1
b. 1
c. 1
d. 0
e. 1
f. 0
g. 1
h. 0
i. 1
100
Operators and Expressions
j. 0
3. Given integer variables x, y, and z with values 10, 7, and 2 respectively. Determine
the valued of each of the following arithmetic expressions.
a. x + y - 2z
b. x / z (x * x +y)
c. (x * y) % z
d. 5 * (x + y + z) – x / z
e. x*y–x*z
f. y * (x + z) * (x – y)
a. 13
b. 535
c.
d.
e.
0
90
50
4
f. 252
4. Using the values given in exercise 3, determine the values for the each af the
following expressions:
a. x++
b. x < 2 && z > 5.0
c. y >= x
d. z != 10
e. x < y || y > z
f. (z * 5) == x
a. 11
b. 0
c. 0
d. 1
e. 1
f. 1
a. =
b. ==
c. =>
d. +=
a. =
b. ==
c. !=
d. !!
101
Fundamentals to Programming
7. If you attempt to add a float, an int and a long, the result will be a(n) ____________.
a. float
b. int
c. long
d. error message
a. char code = 3;
b. char code = "three";
c. char code = "3";
d. char code = '3';
a = 'b';
b = 'c';
c = a;
cout<<a<<b<<c;
Output: bcb
10. Write a complete C++ program that reads two whole numbers into two variables of
type int, and then output both the whole number part and the remainder when first
number is divided by the second. This can be done using the operators / and %.
main()
{
int num1, num2;
cout<<"Enter two whole numbers: ";
cin>>num1>>num2;
cout<<num1<<" divided by "<<num2<<" equals "<<(num1/num2)
<<" with remainder of "<<(num1%num2)<<endl;
return 0;
}
102