lecture 3
DESCRIPTION
Operators and Expressions in C++TRANSCRIPT
AU/MITM/1.6
By Mohammed A. Saleh
1
➩Module 2Fundamentals of C++ - Operators & Expressions – Data I/O – Control Structures – Storage Classes – Arrays and Strings.
2
Arithmetic Operators C++ uses operators to do arithmetic It provides operators for five basic arithmetic
calculations: addition, subtraction, multiplication, division, and taking the modulus
Each of these operators uses two values (called operands) to calculate a final answer.
Together, the operator and its operands constitute an expression. 3
Example
int wheels = 4 + 2; The values 4 and 2 are operands, the +
symbol is the addition operator, and 4 + 2 is an expression whose value is 6.
The % operator finds the modulus of its first operand with respect to the second. That is, it produces the remainder of dividing the first by the second. For example, 19 % 6 is 1 .
4
// arith.cpp -- some C++ arithmetic
#include <iostream>
int main()
{
float hats, heads;
cout << “Enter a number: “;
cin >> hats;
cout << “Enter another number: “;
cin >> heads;
cout << “hats = “ << hats << “; heads = “ << heads << endl;
cout << “hats + heads = “ << hats + heads << endl;
cout << “hats - heads = “ << hats - heads << endl;
cout << “hats * heads = “ << hats * heads << endl;
cout << “hats / heads = “ << hats / heads << endl;
return 0;
} 5
Output for the program:Enter a number: 50.25 Enter another number: 11.17 hats = 50.250000; heads = 11.170000 hats + heads = 61.419998 hats - heads = 39.080002 hats * heads = 561.292480 hats / heads = 4.498657 If you need greater accuracy then use double
or long double. 6
Order of Operation – Operator Precedence and
Associativity Consider this statement:
int flyingpigs = 3 + 4 * 5; // 35 or 23? The 4 appears to be an operand for both the +
and * operators. When this happens, C++ uses precedence
rules to decide which operator is used first.
7
The arithmetic operators follow the usual algebraic precedence, with multiplication, division, and the taking of the modulus done before addition and subtraction. Thus, 3 + 4 * 5 means 3 + (4*5). So the answer is 23, not 35.
Note that *, /, and % all have equal precedence. Similarly, addition and subtraction share a lower precedence.
8
Consider the following:
float logs = 120 / 4 * 5; // 150 or 6? When two operators have the same
precedence, C++ looks at whether the operators have a left-to-right associativity a right-to-left associativity.
L-R associativity means that if two operators acting on the same operand have the same precedence, you apply the left-hand operator first. The reverse is true for R-L. 9
Division Diversion The behavior of this operator depends on the
type of the operands. If both operands are integers, C++ performs
integer division. That means any fractional part of the answer is discarded, making the result an integer.
If one or both operands are floating-point values, the fractional part is kept, making the result floating-point. 10
// divide.cpp -- integer and floating-point division
#include <iostream>
int main()
{
cout << “Integer division: 9/5 = “ << 9 / 5 << endl;
cout << “Floating-point division: 9.0/5.0 = “;
cout << 9.0 / 5.0 << endl;
cout << “Mixed division: 9.0/5 = “ << 9.0 / 5 << endl;
cout << “double constants: 1e7/9.0 = “;
cout << 1.e7 / 9.0 << endl;
cout << “float constants: 1e7f/9.0f = “;
cout << 1.e7f / 9.0f << endl;
return 0;
} 11
Program Output:Integer division: 9/5 = 1 Floating-point division: 9.0/5.0 = 1.800000 Mixed division: 9.0/5 = 1.800000 double constants: 1e7/9.0 = 1111111.111111 float constants: 1e7f/9.0f = 1111111.125000
The division operator represents three distinct operations: int division, float division, and double division. C++ uses the context—in this case the type of operands—to determine which operator is meant.
12
The process of using the same symbol for more than one operation is called operator overloading
Figure 1.0: Division Diversion13
The Modulus Operator The modulus operator returns the remainder
of an integer division. Useful in problems that require dividing a
quantity into different integral units, such as converting inches to feet and inches or converting dollars to quarters, dimes, nickels, and pennies.
Example program:14
// modulus.cpp -- uses % operator to convert lbs to stone #include <iostream> int main() {
const int Lbs_per_stn = 14; int lbs;cout << “Enter your weight in pounds: “; cin >> lbs;int stone = lbs / Lbs_per_stn; // whole stone int pounds = lbs % Lbs_per_stn; // remainder in pounds cout << lbs << “ pounds are “ << stone << “ stone, “ << pounds << “ pound(s).\n”;
return 0; }
15
Sample run of the program:Enter your weight in pounds: 177
184 pounds are 12 stone, 9 pound(s).
16
Relational Expressions C++ provides six relational operators to
compare numbers. Each relational expression reduces to the
bool value true if the comparison is true and to the bool value false if the comparison is false, so these operators are well suited for use in a loop test expression
17
Table 1.0: Relational operators
18
Standard algebraic equality operator or relational operator
C++ equality or relational operator
Example of C++ condition
Meaning of C++ condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
Example tests:for (x = 20; x > 5; x--) // continue while x is greater than 5
for (x = 1; y != x; ++x) // continue while y is not equal to x The relational operators have a lower precedence
than the arithmetic operators. That means this expression:
x + 3 > y - 2 // Expression 1 corresponds to this:(x + 3) > (y - 2) // Expression 2 and not to the following: x + (3 > y) - 2 // Expression 3
19
2000 Prentice Hall, Inc. All rights reserved.
Outline
20
1. Load <iostream>
2. main
2.1 Initialize num1 and num22.1.1 Input data
2.2 if statements
1 // relational.cpp2 // Using if statements, relational3 // operators, and equality operators4 #include <iostream>5678910 int main()11 {12 int num1, num2;1314 cout << "Enter two integers, and I will tell you\n"15 << "the relationships they satisfy: ";16 cin >> num1 >> num2; // read two integers1718 if ( num1 == num2 )19 cout << num1 << " is equal to " << num2 << endl;2021 if ( num1 != num2 )22 cout << num1 << " is not equal to " << num2 << endl;2324 if ( num1 < num2 )25 cout << num1 << " is less than " << num2 << endl;2627 if ( num1 > num2 )28 cout << num1 << " is greater than " << num2 << endl;2930 if ( num1 <= num2 )31 cout << num1 << " is less than or equal to "32 << num2 << endl;33
The if statements test the truth of the condition. If it is true, body of if statement is executed. If not, body is skipped.To include multiple statements in a body, delineate them with braces {}.
Enter two integers, and I will tell you the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7
2000 Prentice Hall, Inc. All rights reserved.
Outline
21
2.3 exit (return 0)
Program Output
34 if ( num1 >= num2 )
35 cout << num1 << " is greater than or equal to "
36 << num2 << endl;
37
38 return 0; // indicate that program ended successfully
39 }
Enter two integers, and I will tell you the relationships they satisfy: 3 73 is not equal to 73 is less than 73 is less than or equal to 7
Enter two integers, and I will tell you the relationships they satisfy: 22 1222 is not equal to 1222 is greater than 1222 is greater than or equal to 12
Enter two integers, and I will tell you the relationships they satisfy: 7 77 is equal to 77 is less than or equal to 77 is greater than or equal to 7
Logical Expressions Often you must test for more than one
condition. For example, for a character to be a lower- case letter, its value must be greater than or equal to ‘a’ and less than or equal to ‘z’
Or, if you ask a user to respond with a y or an n, you want to accept uppercase (Y and N) as well as lowercase.
22
To meet this kind of need, C++ provides three logical operators to combine or modify existing expressions.
The operators are logical OR, written ||; logical AND, written &&; and logical NOT, written !
The Logical OR Operator: || This operator combines two expressions into
one. 23
If either or both of the original expressions is true, or nonzero, the resulting expression has the value true. Otherwise, the expression has the value false.
Example:5 ==5 || 5 == 9 5 > 3 || 5 > 10 5 > 8 || 5 < 10 5 < 8 || 5 > 2
5 > 8 || 5 < 2 24
Table 2.0: The || Operator C++ provides that the ||operator is a sequence
point. That is, any value changes indicated on the left side take place before the right side is evaluated.
Example:i++ < 6 || i == j // take i to be 10 25
// or.cpp -- using the logical OR operator #include <iostream> int main() {
cout << “This program may reformat your hard disk\n” “and destroy all your data.\n” “Do you wish to continue? <y/n> “; char ch; cin >> ch;
if (ch == ‘y’ || ch == ‘Y’) // y or Y cout << “You were warned!\a\a\n”; else if (ch == ‘n’ || ch == ‘N’) // n or N cout << “A wise choice ... bye\n”; Elsecout << “That wasn’t a y or an n, so I guess I’ll “ “trash your disk anyway.\a\a\
a\n”; return 0; } 26
Sample run of the program: This program may reformat your hard disk and destroy all your data. Do you wish to continue? <y/n> NA wise choice ... Bye
The Logical AND Operator: && Like the || operator, the && operator also
combines two expressions into one.
27
The resulting expression has the value true only if both of the original expressions are true.
Examples:5 == 5 && 4 == 4 5 == 3 && 4 == 4 5 > 3 && 5 > 10 5 > 8 && 5 < 10 5 < 8 && 5 > 2 5 > 8 && 5 < 2
28
Like the ||operator, the &&operator acts as a sequence point, so the left side is evaluated.
Table 3.0: The && Operator
29
The Logical NOT Operator: ! The ! operator negates, or reverses the truth
value of, the expression that follows it. That is, if expression is true, then !expression
is false—and vice versa Example:
while (n!=7)
body
30
Logical Operator Facts The C++ logical OR and logical AND
operators have a lower precedence than relational operators.
This means that an expression such as this:
x > 5 && x < 10 is read this way:(x > 5) && (x < 10)
31
The ! operator, on the other hand, has a higher precedence than any of the relational or arithmetic operators.
Therefore, to negate an expression, you should enclose the expression in parentheses, like this:
!(x > 5) // is it false that x is greater than 5 The logical AND operator has a higher
precedence than the logical OR operator. Thus this expression: 32
age > 30 && age < 45 || weight > 300 means the following: (age > 30 && age < 45) || weight >
300 That is, one condition is that age be in the
range 31–44, and the second condition is that weight be greater than 300. The entire expression is true if one or the other or both of these conditions are true.
33
// LAB
# include <iostream># include <conio>int main ()
{
cout << “LET’S CODE \n”;
getch ();
return 0; }34
// Weekend
# include <iostream># include <conio>int main ()
{
cout << “Have A C++ Weekend \n”;
getch ();
return 0; } 35