Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
Visual C++ Programming – Penn Wu, PhD 101
Lecture #4 Operators
Introduction In programming, the term operator refers to a symbol or a keyword that represents a specific
action (known as operation). An operator can operate on one, two or more operands to return a
value as result. The most generic syntax of Visual C++ operators are:
operator operand1
and
operand1 operator operand2
The following is an example of the “increment” operators (++) which works on only one
operand. An integer 5 is assigned to a variable of int type named x. The “increment” operator
adds 1 to the value of x to produce a new value 6. In this example, 5 is the operand.
int main()
{
int x = 5;
MessageBox::Show((++x) + "");
}
The following demonstrates how the “greater than” operator works. The expression reads as “5
is greater than 5.1”; however, its result is false. In this example, 5 is operand1 while 5.1 is
operand2.
5 > 5.1
Arithmetic
operators
Arithmetic operators perform the basic arithmetic operations that involve the calculation of
numeric values represented by literals, variables, other expressions, function and property calls,
and constants. Visaul C++ supports addition, subtraction, multiplication, division, and modulus
operations.
Operator Name Examples Description
+ Addition x = 5 + 3 Adds the two values together
- Subtraction x = 5 – 3 Subtracts the second value from the first.
* Multiplication x = 5 * 3 Multiplies the two values by each other.
/ Division x = 5 / 3 Divides the first value by the second.
% Modulus x = 5 % 3 Returns the remainder of the first value divided by
the second.
The following is the generic syntax. Both n1 and n2 are two numbers, such as 3 - 5, 6.3 * 7, and
4 + 11.5. Yet, programmers frequently declare two variables, such as x and y, to work with the
arithmetic operators.
n1 operator n2
The following code demonstrates how to use variables for arithmetic operations. It is necessary
to note that the “+” sign, as in y + "", is used to “concatenate” the result of calculation with a
Visual C++ Programming – Penn Wu, PhD 102
blank string (""). In this case, “+” is not the addition operator. Again, anything that
concatenates with a string becomes a string. The instructor made this arrangement because the
MessageBox::Show() method can only accept string literal.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
double x = 3.51;
double y = x - 0.57; // subtraction
x = x + 2.672; // addition
MessageBox::Show(y + ""); // concatenation
}
In a nutshell, when the plus sign (+) is placed between two numbers, it denotes the “addition”
operator. When one of the operands is a string literal, as shown below, the plus sign denotes the
“concatenation” operator.
4.12 + ""
The following is a complete code illustrating how the multiplication operator (*) works.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
MessageBox::Show((3.51 * 6.28) + "");
}
The result of the addition (+) operator is the sum of the operands. The result of the subtraction
(–) operator is the difference between the operands. The multiplication (*) operator finds the
product of n1 and n2 by multiplying the first operand (n1) by the second (n2).
The following demonstrates how these operators works. The operations of addition, subtraction,
multiplication, and modulus are easy to understand. Interestingly, the division yields a value of
0.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int x = 3, y = 7;
MessageBox::Show( (x + y) + "\n" + // 10
(x - y) + "\n" + // -4
(x * y) + "\n" + // 21
(x / y) + "\n" + // why 0
(x % y) ); // 3
Visual C++ Programming – Penn Wu, PhD 103
}
In the above code, there is a statement with three (+) signs in it, as shown below, that needs
programmers’ special attention.
str += (x + y) + "\n";
The first (+) sign, as in (+=), tells the compiler to “append” the result of (x + y) + "\n" to
the variable str. The second (+) sign, as in (x + y), is the addition operator that performs the
addition operation. The third (+) sign, as in + "\n", is the concatenation operator that
combines (x + y) with a string "\n".
The division operator (/) yields the result of dividing the first operand by the second. However,
Visual C++ is a type sensitive language, there is a type-related issue. The result of the
following, for example, is 0 (which is arithmetically incorrect), yet it is logically correct in
Visual C++.
int main()
{
MessageBox::Show((3/7) + "");
}
This bias is caused by the strictly regulated declaration of data types. Both 3 and 7 are integer
type (int); therefore, the result of calculation must be based on int type (namely fractional part is
simply truncated). According to arithmetic, the result of 3/7 is 0.4285714285714286. However,
Visual C++ will check the type of both operands and accordingly truncate the fractional part.
Consequently, the result of 3/7 in C++ is 0.
3/7 = 0.428571428571429
One way to avoid this problem is to temporarily cast the types to a proper one. For example,
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
MessageBox::Show( ( (double) 3 / (double) 7 ) + "");
}
In the above code, 3 and 7 are temporarily treated as double type (which allows fractional part),
so the calculation results will be 0.428571428571429 (a double value). Both 3 and 7 will
return to int type after calculation.
The modulus operator (%), also known as “remainder operator”, performs an integer division to
n1 by n2 and returns only the remainder as result. In Visual C++, it uses the following syntax
with the result of operation being a number in the range from 0 and to n2-1.
n1 % n2
In other words, the possible outcome of x % y are in the set {0, 1, 2, ...., y-1}. The following
code illustrates how the modulus operation works. It also proves that the possible outcome of
(i%5) is in the set of {0, 1, 2, 3, 4}.
Visual C++ Programming – Penn Wu, PhD 104
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
MessageBox::Show( (15%5) + "\n" + //0
(16%5) + "\n" + //1
(17%5) + "\n" + //2
(18%5) + "\n" + //3
(19%5) + "\n" + //4
(20%5) + "\n" + //0
(21%5) + "\n" + //1
(22%5) + "\n" + //2
(23%5) + "\n" + //3
(24%5) + "\n" + //4
(25%5) ); //0
}
The following is example that demonstrates how to use the multiplication operator to solve a
Chemistry problem. A 2.0 mole sample of a gas is known to occupy 30.0L of volume. Calculate
the volume (V) for 1.0 mole of the gas according to Avogadro’s Law: Vfinal = z × Vinitial assuming the number of moles of a gas changes by a factor of z and z = 0.5.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
double V = 30.0;
double z = 0.5;
V = z * V;
MessageBox::Show("V (final) = " + V + "L");
}
The output is:
The above code can be simplified to the following.
int main()
{
double V = 30.0;
double z = 0.5;
MessageBox::Show("V (final) = " + (z * V) + "L");
}
Equality
operators and
The “equality” operators determine equality (==) or inequality (!=) of their operands.
Therefore, their return types are Boolean values. It is necessary to note that the equality
Visual C++ Programming – Penn Wu, PhD 105
relational
operators
operator is denoted as (==) which requires two (=) sign. In Visual C++, and many programming
languages, a single (=) signed is used to denotet the “assignment operator” which gives
(assigns) a value to a variable.
Operator Name Sample Description == equal to x == y Is true if the first value is equivalent to the second. != not equal to x != y Is true if the first value is not equal to the second.
In the following example, x = 7.14 assigns 7.14 as the value of a double variable x; therefore,
“=” is the assignment operator. The expression, x == 7.14, evaluates whether or not the value
of x equals 7.14, thus, “==” is the equality operator.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
double x = 7.14; // assignment
Boolean y = (x == 7.14); // equality
MessageBox::Show(y + "");
}
In the following example, 5.0 as a double is equivalent to 5 as an int, yet the inequality operator
(!=) returns True if the operands do not have the same value; otherwise, it returns False. The
output is False.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
MessageBox::Show((5.0 != 5) + "\n" + (5.0 == 5));
}
These operator also apply to String literals.
MessageBox::Show(("Apple" != "apple") + "\n" +
("apple" == "apple"));
Relational
operators
The term “relational operator” (also known as “comparison operators”) refers to the operators
that compares two operands based on <, >, <=, and >= relationships. The value returned is False
(or 0) if the relationship in the expression is false; otherwise, the value returned is True (or 1).
Operator Name Sample Description < less than x < y Is true if the first value is less than the
second.
> greater than x > y Is true if the first value is greater than the
second.
Visual C++ Programming – Penn Wu, PhD 106
<= less than or equal to x <= y Is true if the first value is less than or
equal to the second.
>= greater than or equal to x >= y Is true if the first value is greater than or
equal to the second.
The following example illustrates how they work. By the in some languages as well as some
C++ compilers, 0 indicates false and 1 indicates true.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int x=5, y=7;
MessageBox::Show( (x==y) + "\n" +
(x!=y) + "\n" +
(x<y) + "\n" +
(x>y) + "\n" +
(x<=y) + "\n" +
(x>=y) );
}
The following is another example.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
MessageBox::Show( (5.14 > 5) + "\n" +
(3 < 2.09) + "\n" +
(6.14 <= 2.397) + "\n" +
(1.98 >= 0.25) );
}
In Standard C++, the expressions in the above example must be enclosed in parentheses
because the stream insertion operator (<<) has higher precedence than the relational operators.
//To compile use: cl.exe filename.cpp
#include <iostream>
using namespace std;
int main()
{
cout << (4 < 3) << endl;
}
Assignment
operators
As discussed previously, an assignment operator gives a value to an object like a variable, as
shown below. Interestingly, the assignment operator can combine with arithmetic operators to
form “compound assignment operators”.
double PI = 3.1512;
Visual C++ Programming – Penn Wu, PhD 107
String^ FullName = "Jennifer Lopez";
A “compound assignment operator” consists of an arithmetic operator and the assignment
operator to perform two operations in a hybrid mode and then update the the left operand with
the result of operation. The -= operator, for example, is the combination of subtraction (-) and
assignment (=) operators. The following statement means “to subtract 4 from x and assign the
result to x”.
x -=4;
The above statement is functionally equivalent to the following.
x = x – 4;
The following table lists all the compound assignment operators.
Operator Example Operation Explanation
+= x += 3 x = x + 3 x = x + 3 means “add 3 to the current value of x and
then assign the result of addition to x”.
–= x -= 3 x = x – 3 x = x - 3 means “subtract 3 from the current value of
x and then assign the result to x”.
*= x *= 3 x = x * 3 x = x * 3 means “multiply the current value of x by 3
and then assign the result to x”.
/= x /= 3 x = x / 3 x = x / 3 means “divide the current value of x by 3
and then assign the result to x”.
%= x %= 3 x = x % 3 x = x % 3 means “find the integer remainder of the
current value of x divided by 3 and then assign the
result to x”.
The following is a complete code that demonstrates how to use the (+=) operator. The
expression x += 3 is equivalent to x = x + 3. According to the above code, x was originally
assigned to be 4. The expression x + 3 forces the computer to add 3 to x; therefore, the resulting
value of a becomes 7. Similarly, y %= 5 is equivalent to y = y % 5, while y is initially set to 6.
The calculation is thus based on y = 6%5, and the result is 1.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int x = 4, y = 6;
double z = 6.9, w = 7.5;
x += 3; // x becomes 7
y %= 5; // y becomes 1
z -= 4.7; // z becomes 3.2
w /= 0.5; // w becomes 15
MessageBox::Show(x + "\n" + y + "\n" + z + "\n" + w);
}
The expression
Visual C++ Programming – Penn Wu, PhD 108
a *= (b + c)
is equivalent to
a = a * (b + c)
or
a = a * b + a * c
but not
a = a * b + c
The following is a complete code that illustrates such calculations.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int b = 4, c = 3;
int a = 5;
a *= (b + c);
MessageBox::Show(a + ""); // 35
}
In Visual C++, the += operator can be used to “append” string literals as discussed previously.
The word “append” means “add new content to the existing contents without replacing the
existing contents”. In the following example, “str” is declared as variable of String type whose
value is nullptr (a Visual C++ keyword that means “nothing”). In each of the three bold-faced
lines, the += operator will “append” a string literal to “str”; therefore, the content of “str” will
grow statement by statement. Finally, the message box display the “appended” string literal.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace
System::Windows::Forms;
int main()
{
String^ str = nullptr;
str += (3 > 2) + "\n";
str += (4.1 < 6.35) + "\n";
str += ("Tree" == "tree");
MessageBox::Show(str);
}
This “text appending” technique will be used throughout this course.
Increment
operators
Increment and decrement operators can add or subtract a given number (n) from their operands.
The simplest form of increment operation is “++” which means to increase the value by 1. The
Visual C++ Programming – Penn Wu, PhD 109
simplest form of decrement operation is “--" which means to decrease the value by 1. When the
increment or decrement is not 1, the format is: +=n or -=n, where n is a number other than 1.
Operand Name Sample Description
++ Increment by 1 x++; Returns the value of x + 1.
-- Decrement by 1 y--; Returns the value of y - 1.
+=n Increment by n x +=2.1 Returns the value of x + 2.1.
-=n Decrement by n y -= 2.1 Returns the value of y - 2.1.
The effect of applying the increment operator (++) to an operand is that the operand’s value is
increased by one unit. Similarly, the effect of decrement operator (--) is that the operand’s value
is decreased by one unit. The effect of +=n is to increase the value by n, and the effect of -=n is
to decrease the value by n. The following example demonstrates how the simplest form of
increment and decrement operators work.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int x = 4, y = 3;
x++; // x becomes 5
y--; // y becomes 2
MessageBox::Show(x + "\n" + y);
}
Interestingly, Visual C++ provides clearly distinguishes prefix- from postfix-increment as well
as prefix- and postfix-decrement operators. Depending on how programmers place the operator,
the change in value (increment or decrement) could happen before or after the value is read.
Name Sample Description
Postfix-increment x++; Returns x, then increases it by 1.
Prefix-increment ++x; Increases x by 1, then returns it.
Postfix-decrement y--; Returns y, then decreases it by 1.
Prefix-decrement --y; Decreases y by 1, the returns it.
The following example illustrates the differences:
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int a=3, b=3, c=3, d=3;
String^ str = (a++) + "\n"; //increment happens after a is read
str += (++b) + "\n"; //increment happens before b is read
str += (c--) + "\n"; //decrement happens after c is read
str += (--d) + "\n"; //decrement happens before d is read
MessageBox::Show(str);
}
Visual C++ Programming – Penn Wu, PhD 110
The output looks:
3
4
3
2
Increment and decrement operations also apply to skip counting. The A = {1, 4, 7, 10, 13} is
incremented by 3. The set B = {10, 8, 6, 4, 2, 0} is decremented by 2. Their values increase or
decrease by a number larger than 1. In such case, the increment and decrement operators are
denoted by +=n and -=n, in which n is a number other than 1 (such as 4 or 0.1). The following
is an example.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int x=15, y=12;
x += 5;
y -= 2;
MessageBox::Show(x + "\n" + y);
}
The output of th above code is shown below. 20 is the result of 15 + 5, while 10 is the result of
12 - 2.
20
10
The value of n in +=n and -=n does not have to be an integer, it could be a floating point value,
as shown below.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
double x = 6.24, y = 21.72;
x += 0.15;
y -= 1.26;
MessageBox::Show(x + "\n" + y);
}
The output of the abov code is:
6.39
20.46
Visual C++ Programming – Penn Wu, PhD 111
Logical
operators
The logical operators like && (AND) and || (OR) are used to combine multiple relational or
equality expressions into one single expression known as “hybrid expression”. They enable
programmers to make a decision based on multiple conditions. Each operand is considered a
condition that can be evaluated to a true or false value. Then the value of the conditions is used
to determine the hybrid expression.
In the following example, (2>3) and (3>1) are two operands while “&&” denote the logical
“AND” operator. (2>3) is a false while (3>1) is true.
(2>3) && (3>1)
The result of the above “hybrid expression” is determined by the “&&” operator. The following
table is a list of these operators and their definitions. By the way, the logical negation operator
(!) simply reverses the Boolean status of its operand.
Operand Name Sample Description && AND x && y Is true if both x and y are true.
|| OR x || y Is true if either x or y is true.
! NOT !x Is true if x is not true.
The logical AND operator (&&) returns the true if both operands are true; otherwise, it returns
false. The hybrid expression, ((2>3) && (3>1)), is False because (2>3) is false.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
MessageBox::Show( ((2>3) && (3>1)) + ""); //False
}
In the following example, both (3>2) and (2>1.5) are true, so the hybrid expression is true.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
MessageBox::Show( ((3>2) && (2>1.5)) + ""); //True
}
The logical “AND” operators can “nest”. In the following example, the hybrid expression
((3<4.1) && (4>2.5)) is true and is treated as an operand.
(3<4.1) && (4>2.5) && (7!=7)
The following is the sample code. The output is False because (7!=7) is false.
#using <System.dll>
#using <System.Windows.Forms.dll>
Visual C++ Programming – Penn Wu, PhD 112
using namespace System;
using namespace System::Windows::Forms;
int main()
{
MessageBox::Show( ((3<4.1) && (4>2.5) && (7!=7)) + "");
}
Students can use the Truth Table to learn how the “AND” operator works.
Inputs AND
A B A && B
0 0 0
0 1 0
1 0 0
1 1 1
Do not get scared by the academic terms! People actually use Boolean logic in their everyday
life. For example, when a lady just said, “My name is Jennifer and I am a doctor”. If the lady is
actually named Megan, or if she is actually a cook, then her statement would be false (the value
is 0).
The statement above is actually made of two expressions or values: “My name is Jennifer” and
“I am a doctor”. Each of those, by itself, is true or false. The “AND” in the sentence is the
logical operator, which makes one expression out of two.
When applying them to the truth table, “My name is Jennifer” is input A, while “I am a doctor”
is input B. The entire sentence is then denoted as A AND B. If her name is Jennifer (the value is
1) but she is not a doctor (the value is 0), the statement is false according to A AND B, which
means both A and B must be true.
The logical OR operator (||) returns true if either or both operands is true. In the following
example, (2>3) is false while (3>1) is true. The expression, ((2>3) || (3>1)), is True
because the definition is “as long as one of the operand is true, the hybrid expression is true”.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
String^ str = ((2>3) || (3>1)) + "\n"; // True because (3>1)
MessageBox::Show(str);
}
The operands to the logical OR operator need not be of the same type, but they must be of
integral or pointer type. The operands are commonly relational or equality expressions. The first
operand is completely evaluated, and all side effects are completed before continuing evaluation
of the logical OR expression. The second operand is evaluated only if the first operand
evaluates to false (0). This eliminates needless evaluation of the second operand when the
logical OR expression is true.
Visual C++ Programming – Penn Wu, PhD 113
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int a = 5, b = 10, c = 15;
String^ str = "";
str += (a < b || b > c) + "\n"; //True
str += (a > b || b > c) + "\n"; //False
MessageBox::Show(str);
}
Students can use the Truth Table to learn how the logical “OR” operator works.
Inputs OR
A B A || B
0 0 0
0 1 1
1 0 1
1 1 1
The NOT (!) operator simply negates the expression. This operator determines whether the
operand evaluates to 0 (false) or nonzero (true). The expression yields the value true if the
operand evaluates to false (0), and yields the value false if the operand evaluates to true
(nonzero). The operand is implicitly converted to bool, and the type of the result is bool. The
following is true because (2<0) is false. Yet, the statement literally means “(2<0) is not true”.
!(2<0)
The following two expressions are equivalent. The expression !(2==3) literally means “(2==3)
is not true”, and can be logically interpreted as “2 is not equal to 3” which can be express as
(2!=3).
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
String^ str = !(2==3) + "\n"; //True
str += (2!=3) + "\n"; //True
str += ( !(2==3) == (2!=3) ); //True
MessageBox::Show(str);
}
The following is another sample code:
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
Visual C++ Programming – Penn Wu, PhD 114
int main()
{
int a = 5;
String^ str = "";
str += !(a==6) + " "; // True
str += (a!=6) + " "; // True
str += !(a==5) + " "; // False
str += (a!=5); // False
MessageBox::Show(str);
}
Students can use the Truth Table to learn how the “NOT” operator works.
Inputs NOT
A B !A !B
0 0 1 1
0 1 1 0
1 0 0 1
1 1 0 0
In the following example, both condition x>4 and y>5 are true.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int x=5, y=7;
String^ str = (x>4 && y>5) + "\n"; //True
str += (x>4 || y>5) + "\n"; //True
str += !(x>4) + "\n"; //False
MessageBox::Show(str);
}
Bitwise
operators
Bitwise operators must operate in binary format. They are logical operators that compares each
bit of its first operand to the corresponding bit of its second operand in order to evaluate the
expression and return a value as result. The following is the syntax, in which both operands (n1
and n2) must be of integral types.
n1 operator n2
It is easier to understand how bitwise operators work by using binary form of a number. The
following lists two numbers, 5 and 6, and their binary equivalents in the 8-bit format.
Number 8-bit format
5 00000101
6 00000110
The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit
of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the
corresponding result bit is set to 0. The following uses eight-bit format of two binary values of
Visual C++ Programming – Penn Wu, PhD 115
5 and 6 to explain how the bitwise AND operator works. The result of (5 & 6) in binary is
0000100, which is equivalent to 4. Therefore, the result of (5 & 6) is 4.
Number 8-bit format
5 00000101
6 00000110
5 & 6 = 4 00000100
The bitwise inclusive OR operator (|) compares each bit of its first operand to the corresponding
bit of its second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the
corresponding result bit is set to 0.
Number 8-bit format
5 00000101
6 00000110
5 | 6 = 7 00000111
The bitwise XOR operator (^), pronounced as “exclusive OR”, compares each bit of its first
operand to the corresponding bit of its second operand. This operator looks at the binary
representation of the two operands and does a bitwise exclusive OR operation on them. If one
bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the
corresponding result bit is set to 0.
Number 8-bit format
5 00000101
6 00000110
5 ^ 6 = 3 00000011
The following is a complete code that demonstrates how these bitwise operators work.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
String^ str = (5 & 6) + "\n"; // 4
str += (5 | 6) + "\n"; // 7
str += (5 ^ 6) + "\n"; // 3
MessageBox::Show(str);
}
Bitwise NOT operator (~) performs a bitwise NOT (negation) operation on an operand. This
operator is presumably the easiest to understand; however, it is the most confusing one due to
the total number of bit the data has. The following shows the differences in result of (~5) when
the numbers of bit are different.
Number 8-bit format 16-bit format
5 00000101 00000000 00000101
~5 11111010 11111111 11111010
To see the result of (~5) in Visual C++, use the following code. By the way, the result might
vary from compiler to compiler.
Visual C++ Programming – Penn Wu, PhD 116
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
unsigned __int16 x = 5;
unsigned __int32 y = 5;
unsigned __int64 z = 5;
String^ str = sizeof(x) + " bytes: " + ~x + "\n";
str += sizeof(y) + " bytes: " + ~y + "\n";
str += sizeof(z) + " bytes: " + ~z + "\n";
MessageBox::Show(str);
}
There are two bitwise “shift” operators: right-shift (>>) and left-shift (<<) operators. The right-
shift operator (>>) moves the bits of operand to the right, and the left-shift operator (<<) moves
the bits of operand to the left.
Operator Notation Syntax Description
left shift << x<<n all bits in x shifted left by n places
right shift >> x>>n all bits in x shifted right by n places
The following explains how these two operators work.
Number 8-bit format Explanation
5 00000101 • 5 in eight-bit binary format
•
5 << 2 = 20 0000010100 • Move every bit 2 places toward the left.
• Add 0’s to the blank bit on the left.
•
5 >> 2 = 1 000001 • Move every bit 2 places toward the right.
• Omit the bit(s) that no longer has/have places.
The following is a complete code.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
String^ str = (5 << 2) + "\n"; // 20
str += (5 >> 2) + "\n"; // 1
MessageBox::Show(str);
}
They right-shift and left-shift operators are confusing to newbies because the Standard C++ also
defines (>>) and (<<) as stream extraction operator (>>) and the stream insertion operator (<<).
They are also known as input (>>) and output (<<) operators in Standard C++. The instructor
wrote the following code with the intention to help students distinguish them. Basically, both
Visual C++ Programming – Penn Wu, PhD 117
insertion and extraction operators must be paired with “cout” and “cin” methods, while right-
shift and left-shift are followed by an integer.
//To compile use: cl.exe filename.cpp
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter a number: "; // insertion
cin >> x; // extraction
cout << (x<<2) << endl;
cout << (x>>2) << endl;
}
Conditional
operator
The conditional operator evaluates a Boolean condition to determine which of the two possible
results to produce. The following is the syntax. A Boolean expression is followed by a question
mark (?), followed by two expressions separated by a colon (:). When the condition is true,
result1 is produced; otherwise, result2 is produced.
condition ? result1 : result2
The expressions placed before and after ? as well as the one placed after : are components of
one single statement. In the following example, (7==5) is false; therefore, the variable “a” is
assigned 3 as value.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int a = (7==5) ? 4 : 3; //3
MessageBox::Show(a + "");
}
Interestingly, (7==(5+2)) in the following is true; therefore, “a” equals to 4.
int a = (7==(5+2)) ? 4 : 3;
In the following example, (i > j) is the condition to test. Since i=1 and j=2, (i>j) is false, the
result is 2. The expression i > j ? i : j actually means “if i > j then i; otherwise j”.
According to the above code, i is less than j; therefore, the result is 2.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int i = 1, j = 2;
MessageBox::Show( (i > j ? i : j) + " is greater." );
Visual C++ Programming – Penn Wu, PhD 118
}
Also, in the following example, a is 2 and b is 7, so the expression being evaluated (a>b) is not
true, thus the first value specified after the question mark was discarded in favor of the second
value (the one after the colon) which was b, with a value of 7.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int a=2, b=7, c;
c = (a>b) ? a : b;
MessageBox::Show(c + "");
}
Conditional operator can “next” which means “one inside another”. In the following, (g >=
60) ? "D" : "E" is the result2 (the “false” part) of the (g >= 70) ? "C" : result2
statement. Similarly, (g >= 70) ? "C" : (g >= 60) ? "D" : "E" is the result2 of the
(g >= 80) ? "B" : result2 statement.
( (g >= 90) ? "A" : (g >= 80) ? "B" : (g >= 70) ? "C" : (g >=
60) ? "D" : "E" );
The following is a sample code that can determine a student’s grade.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
double g = 45.8;
String^ grade = ( (g >= 90) ? "A" : (g >= 80) ? "B" : (g >=
70) ? "C" : (g >= 60) ? "D" : "E" );
MessageBox::Show(grade);
}
The comma
operator
The comma operator (,) is used to separate two expressions that are included in one single
statement. However, they are more commonly used in C++ functions to separate two or more
parameters. The following code, for example, produces 5 as output. During the processing, the
express (b=3, b+2) assigns 3 as value to b, and then assign b+2 to variable a. So, at the end,
variable a will contain the value 5 while variable b would contain value 3.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
Visual C++ Programming – Penn Wu, PhD 119
{
int a, b; // variable declaration
a = (b=3, b+2);
MessageBox::Show(a + "\n" + b);
}
Interestingly, when a comma-seperated expression has to be evaluated, only the leftmost and
the rightmost expressions are considered. In the following, the leftmost (b=3) and the rightmost
(b+4) expressions are picked for calculation. The middle (b+2) is completely ignored. The
output is 7 because of 3+4.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int a, b; // variable declaration
a = (b=3, b+2, b+4);
MessageBox::Show(a + "\n" + b);
}
Similarly, the output of the following is 9. Both b+2 and b+4 are ignored.
a = (b=3, b+2, b+4, b+6);
A real-world
example
Avogadro’s law is an important Chemistry concept that states that, at the same temperature and
pressure, equal volumes of all gases have the same number of molecules. In other word, the law
says that “volume is directly proportional to the number of moles.” The equation is typically
expressed as the following, where v1 and v2 are volumes while n1 and n2 are the moles.
𝑣1
𝑛1 =
𝑣2
𝑛2
Programmers can create an application to help solving the following problem.
“A 6.00 L sample at 25.0 °C and 2.00 atm contains 0.500 mol of gas. If we add 0.250
mol of gas at the same pressure and temperature, what is the final total volume of the
gas?”
The following is the sample code.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
float v1 = 6.00;
float n1 = 0.5;
float n2 = 0.5 + 0.25;
float v2 = v1 * n2 / n1;
Visual C++ Programming – Penn Wu, PhD 120
MessageBox::Show("The final total volume is " + v2);
return 0;
}
The following is a sample output.
Review
Questions
1. The result of the following in C++ is __.
int main()
{
int r = 65 / 11;
MessageBox::Show(r + "");
}
A. 65 / 11
B. 5.9090909090909
C. 5
D. 6
2. Given the following code segments, the output is __.
int main()
{
int x=15;
x+=5;
MessageBox::Show(""+x);
}
A. 15
B. 20
C. 5
D. 0
3. Given the following code segments, the output is __.
int main()
{
int x=5;
MessageBox::Show("" + !(x>4));
}
A. False
B. True
C. x>4
D. !(x>4)
4. Given the following code segments, the output is __.
int main()
{
int a=3;
Visual C++ Programming – Penn Wu, PhD 121
MessageBox::Show("" + (--a));
}
A. 2
B. 3
C. 4
D. (--a)
5. Which is equivalent to the following statement?
x *= (y + z);
A. x = x * y + z
B. x = x * y + x * z
C. x = y + x * z
D. x = x * x + y * z
6. Given the following code, the output is __.
int main()
{
int x = 5, y = 3;
MessageBox::Show( (x > y ? "true" : "false") );
}
A. 5
B. 3
C. true
D. false
7. Given the following code segments, which is the ouput?
int main()
{
int x = 7;
MessageBox::Show( (x == (int) 7.6) + "" );
}
A. 0
B. x == (int) 7.6
C. True
D. False
8. Given the following code segments, which is the ouput?
int main()
{
MessageBox::Show( ((4<5) && (3>1.5) && (7.2>6)) + "" );
}
A. 0
B. (4<5) && (3>1.5) && (7.2>6)
C. True
D. False
9. Given the following code segments, which is the ouput?
int main()
{
Visual C++ Programming – Penn Wu, PhD 122
int x = 8, y = 4;
MessageBox::Show( (x ^ y) + "" );
}
A. 4
B. 8
C. 12
D. x ^ y
10. Given the following code segments, which is the ouput?
int main()
{
int x = 5, y = 3;
MessageBox::Show( (x << y) + "" );
}
A. 8
B. 40
C. 5
D. 2
Visual C++ Programming – Penn Wu, PhD 123
Lab #4 Operators
Learning Activity #1: Basic Operators
1. Create a directory called C:\cis223 if necessary.
2. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223
directory.
3. Make sure the InputBox.cpp file is in the “C:\cis223” directory. (See Lab #2 for details)
4. Type notepad lab4_1.cpp and press [Enter] to use Notepad to create a new source file called lab4_1.cpp
with the following contents. The objective is to demonstrate how operators works in Visual C++.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
/*----Arithmetic operator----*/
int a=7, b=3, c, d;
String^ str = (a+b) + "\n"; // addition
str += (a-b) + "\n"; // subtration
str += (a*b) + "\n"; // multiplication
str += (a/b) + "\n"; // division, why is the result 2?
str += ((double) a/ (double) b) + "\n";// type casting
str += (a%b) + "\n"; //modulus
/*----increment/decrement----*/
a=3, b=3, c=3, d=3;
str += (a++) + "\n"; //increment happens after a is read
str += (++b) + "\n"; //increment happens before b is read
str += (c--) + "\n"; //decrement happens after c is read
str += (--d) + "\n"; //decrement happens before d is read
/*----compound assignment-----*/
int x=15, y=12;
x += 5;
y -= 2;
str += x + "\n";
str += y + "\n";
/*----comparison/equality----*/
x=5, y=7;
str += (x==y) + "\n";
str += (x!=y) + "\n";
str += (x<y) + "\n";
str += (x>y) + "\n";
str += (x<=y) + "\n";
str += (x>=y) + "\n";
/*----logical-----*/
int m=5;
int n=7;
str += (m>4 && n>5) + "\n";
Visual C++ Programming – Penn Wu, PhD 124
str += (m>4 || n>5) + "\n";
str += (!m>4) + "\n";
MessageBox::Show(str);
}
5. Type cl /clr lab4_1.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile.
6. Type lab4_1.exe and press [Enter] to test the executable file.
7. Download the “assignment template” and rename it to lab4.doc if necessary. Capture a screen shot similar to the
above figures and paste it to the Word document named lab4.doc (or .docx).
Learning Activity #2: Application of arithmetic operators
1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223
directory.
2. Type notepad lab4_2.cpp and press [Enter] to use Notepad to create a new source file called lab4_4.cpp
with the following contents. The objective is to demonstrate how to use arithmetic operators to perform
arithmetic calculations based on two formulas: C = (F-32) × 5
9 and F = C ×
9
5 +32.
#include "InputBox.cpp"
int main()
{
double Fd, Cd; //declare two double variables
/*----F to C----*/
// calling the Input method
String^ str = InputBox::Show("Enter a temperature value in Fahrenheit: ");
Fd = Convert::ToDouble(str); // convert to double
// Math::Round(value, 2) round to 2nd digit next to decimal point.
Cd = Math::Round(5.0 * (Fd-32) / 9.0, 2);
MessageBox::Show("The value in Celsius is " + Cd + "!");
/*----C to F----*/
str = InputBox::Show("Enter a temperature value in Celsius: ");
Cd = Convert::ToDouble(str);
Fd = Math::Round((Cd * (9.0 / 5.0) + 32), 2);
Visual C++ Programming – Penn Wu, PhD 125
MessageBox::Show("The value in Fahrenheit is " + Fd + "!");
}
3. Type cl /clr lab4_2.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile
the source file to create the executable object file.
4. Type lab4_2.exe and press [Enter] to test the executable file. A sample output looks:
and and and
5. Capture a screen shot similar to the above figure and paste it to the Word document named lab4.doc (or .docx).
Learning Activity #3: Application of increment operators
1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223
directory.
2. Type notepad lab4_3.cpp and press [Enter] to use Notepad to create a new source file called lab4_3.cpp
with the following contents. The objective is to demonstrate how increment and decrement operators can
perform calculation based on skip counting. There are 12 inches in 1 foot, so the increment is 1/12 feet. The
grading criterial use 10 points as interval.
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Windows::Forms;
int main()
{
int inch = 0;
float ft = 0;
float n = (1.0f/12.0f); // increment of inch-to-foot
String^ str = "Inch\tFoot\n";
str += inch + "\t" + ft + "\n"; // 12 inches = 1 foot
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 1
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 2
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 3
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 4
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 5
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 6
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 7
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 8
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 9
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 10
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 11
str += (++inch) + "\t" + Math::Round((ft += n), 2) + "\n"; // 12
int gd = 100;
char c = 'A';
str += "\nPoints\tGrade\n";
str += (gd -= 10) + " ~ \t" + Convert::ToChar(c++) + "\n";
str += (gd -= 10) + " ~ \t" + Convert::ToChar(c++) + "\n";
str += (gd -= 10) + " ~ \t" + Convert::ToChar(c++) + "\n";
str += (gd -= 10) + " ~ \t" + Convert::ToChar(c++) + "\n";
Visual C++ Programming – Penn Wu, PhD 126
MessageBox::Show(str);
}
3. Type cl /clr lab4_3.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile
the source file to create the executable object file.
4. Type lab4_3.exe and press [Enter] to test the executable file. A sample output looks:
5. Capture a screen shot similar to the above figure and paste it to the Word document named lab4.doc (or .docx).
Learning Activity #4:
1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223
directory.
2. Type notepad lab4_4.cpp and press [Enter] to use Notepad to create a new source file called lab4_1.cpp
with the following contents. The objective is to demonstrate how comparison operators can help in decision
making.
#include "InputBox.cpp"
int main()
{
String^ str = nullptr;
int age = Convert::ToInt32(InputBox::Show("How old are you?"));
str += "Allowed to enter Casino: " + (age >= 21) + "\n";
String^ gender = InputBox::Show("Enter your gender:");
gender = gender->ToUpper();
Char g = gender[0];
str += "Candiate of the Woman STEM Scholarship: " + (g == 'F') + "\n";
float gpa = Convert::ToSingle(InputBox::Show("Enter your GPA:"));
str += "Meet the minimum GPA requirement: " + (gpa >= 3.5) + "\n";
str += "Will you get the Woman STEM scholarship?" + ((g == 'F') && (gpa >= 3.5)) +
"\n";
MessageBox::Show(str);
}
Visual C++ Programming – Penn Wu, PhD 127
3. Type cl /clr lab4_4.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile.
4. Type lab4_4.exe and press [Enter] to test the executable file. A sample output looks:
5. Download the “assignment template” and rename it to lab4.doc if necessary. Capture a screen shot similar to the
above figures and paste it to the Word document named lab4.doc (or .docx).
Learning Activity #5: Application Bitwise OR operator
1. Launch the Developer Command Prompt (not the regular Command Prompt) and change to the C:\cis223
directory.
2. Type notepad lab4_5.cpp and press [Enter] to use Notepad to create a new source file called lab4_5.cpp
with the following contents. The objective is to demonstrate how to use the bitwise OR operator as encryption
and decryption algorithm.
#include "InputBox.cpp"
int main()
{
/*-------encryption-----*/
String^ plaintext = InputBox::Show("Enter a password of 8 letters:");
int key = Convert::ToInt32(InputBox::Show("Enter a positive integer between 0 and
10:"));
String^ cipher = Convert::ToChar((char) plaintext[0] ^ key) + "" +
Convert::ToChar((char) plaintext[1] ^ key) + "" +
Convert::ToChar((char) plaintext[2] ^ key) + "" +
Convert::ToChar((char) plaintext[3] ^ key) + "" +
Convert::ToChar((char) plaintext[4] ^ key) + "" +
Convert::ToChar((char) plaintext[5] ^ key) + "" +
Convert::ToChar((char) plaintext[6] ^ key) + "" +
Convert::ToChar((char) plaintext[7] ^ key);
MessageBox::Show(cipher);
/*-------decryption-----*/
cipher = InputBox::Show("Enter the ciphertext:");
key = Convert::ToInt32(InputBox::Show("Enter the key:"));
plaintext = Convert::ToChar((char) cipher[0] ^ key) + "" +
Convert::ToChar((char) cipher[1] ^ key) + "" +
Convert::ToChar((char) cipher[2] ^ key) + "" +
Convert::ToChar((char) cipher[3] ^ key) + "" +
Convert::ToChar((char) cipher[4] ^ key) + "" +
Convert::ToChar((char) cipher[5] ^ key) + "" +
Convert::ToChar((char) cipher[6] ^ key) + "" +
Convert::ToChar((char) cipher[7] ^ key);
MessageBox::Show(plaintext);
}
Visual C++ Programming – Penn Wu, PhD 128
3. Type cl /clr lab4_5.cpp /link /subsystem:windows /ENTRY:main and press [Enter] to compile
the source file to create the executable object file.
4. Type lab4_5.exe and press [Enter] to test the executable file. A sample output looks:
and
5. Capture a screen shot similar to the above figure and paste it to the Word document named lab4.doc (or .docx).
Submittal
1. Complete all the 5 learning activities and the programming exercise in this lab.
2. Create a .zip file named lab4.zip containing ONLY the following self-executable files.
• Lab4_1.exe
• Lab4_2.exe
• Lab4_3.exe
• Lab4_4.exe
• Lab4_5.exe
• Lab4.doc (or lab4.docx or .pdf) [You may be given zero point if this Word document is missing]
3. Log in to course web site (e.g. Canvas or Blackboard) and enter the course site.
4. Upload the zipped file to Question 11 of Assignment as response.
Programming Exercise 04:
1. Launch the Developer Command Prompt.
2. Use Notepad to create a new text file named ex04.cpp.
3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one).
//File Name: ex04.cpp
//Programmer: [YourFullNameHere]
4. Write codes that will ask users to enter today’s exchange rate between U.S. dollars and Japanese Yen and the
amount of U.S. dollars to exchange. With the assumption that the bank will charge 0.1% of handling fee,
perform a calculation using the following formula, and then display the total the person can get in Japanese
Yen.
amount in Yen = exchange rate × amount in US$ × (1-0.1/100)
5. Be sure to use the “InputBox.cpp” file to display the input dialog box. Make sure the output will be similar to
the following.
Visual C++ Programming – Penn Wu, PhD 129
6. Compile the source code to produce executable code.
7. Download the “programming exercise template” and rename it to ex04.doc if necessary. Copy your source
code to the file and then capture the screen shot(s) similar to the above ones and paste it to the Word document
named “ex04.doc” (or .docx).
8. Compress the source file (ex04.cpp), executable code (ex04.exe), and Word document (ex04.doc) to a .zip file
named “ex04.zip”.
Grading criteria:
You will earn credit only when the following requirements are fulfilled. No partial credit is given.
• You successfully submit both source file and executable file.
• Your source code must be fully functional and may not contain syntax errors in order to earn credit.
• Your executable file (program) must be executable to earn credit.
Threaded Discussion
Note: Students are required to participate in the thread discussion on a weekly basis. Student must post at
least two messages as responses to the question every week. Each message must be posted on a
different date. Grading is based on quality of the message.
Question:
Can you provide an example to show how the logical operators are useful in decision making? [There
is never a right-or-wrong answer for this question. Please free feel to express your opinion.]
Be sure to use proper college level of writing. Do not use texting language.