FunctionX Tutorials

Logical Comparisons

 

Logical Operators

 

Introduction

A program is a series of instructions that ask the computer (actually the compiler) to check some situations and to act accordingly. To check such situations, the computer spends a great deal of its time performing comparisons between values. A comparison is a Boolean operation that produces a true or a false result, depending on the values on which the comparison is performed.

A comparison is performed between two values of the same type; for example, you can compare two numbers, two characters, or the names of two cities. On the other hand, a comparison between two disparate values doesn't bear any meaning. For example, it is difficult to compare a telephone number and somebody's age, or a music category and the distance between two points. Like the binary arithmetic operations, the comparison operations are performed on two values. Unlike arithmetic operations where results are varied, a comparison produces only one of two results. The result can be a logical true or false. When a comparison is true, it has an integral value of 1 or positive; that is, a value greater than 0. If the comparison is not true, it is considered false and carries an integral value of 0.

The C++ language is equipped with various operators used to perform any type of comparison between similar values. The values could be numeric, strings, or objects (operations on objects are customized in a process referred to as Operator Overloading).

 

The Equality Operator ==

To compare two variables for equality, C++ uses the == operator. Its syntax is:

Value1 == Value2

The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false or 0.
 

Equalilty Flowchart

Most of the comparisons performed in C++ will be applied to conditional statements; but because a comparison operation produces an integral result, the result of the comparison can be displayed on the monitor screen using a cout extractor. Here is an example:
 

#include <iostream>
using namespace std;

int main()
{
  int Value = 15;

  cout << "Comparison of Value == 32 produces " << (Value == 32) << "\n\n";

  return 0;
}

The result of a comparison can also be assigned to a variable. As done with the cout extractor, to store the result of a comparison, you should include the comparison operation between parentheses. Here is an example:

#include <iostream>
using namespace std;

int main()
{
  int Value1 = 15;
  int Value2 = (Value1 == 24);

  cout << "Value 1 = " << Value1 << "\n";
  cout << "Value 2 = " << Value2 << "\n";
  cout << "Comparison of Value1 == 15 produces " << (Value1 == 15) << "\n\n";

  return 0;
}
This would produce:
Value 1 = 15
Value 2 = 0
Comparison of Value1 == 15 produces 1
 
 

Very important

The equality operator and the assignment operator are different. When writing StudentAge = 12, this means the constant value 12 is assigned to the variable StudentAge. The variable StudentAge can change anytime and can be assigned another value. The constant 12 can never change and is always 12. The variable StudentAge is usually on the left side of the assignment operator. A constant, such as 12, is always on the right side and can never be on the left side of the assignment operator. This means you can write StudentAge = 12 but never 12 = StudentAge because when writing StudentAge = 12, you are modifying the variable StudentAge from any previous value to 12. Attempting to write 12 = StudentAge means you want to modify the constant integer 12 and give it a new value which is StudentAge: you would receive an error.NumberOfStudents1 == NumberOfStudents2 means both variables exactly mean the same thing. Whether using the first or the second, the compiler considers each as meaning the other.

 

The Logical Not Operator !

When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. C++ considers that a variable whose value is null is stern. To render a variable unavailable during the evolution of a program, apply the logical not operator which is !. Its syntax is:

!Value

There are two main ways you can use the logical not operator. As we will learn when studying conditional statements, the most classic way of using the logical not operator is to check the state of a variable.

To nullify a variable, you can write the exclamation point to its left. When used like that, you can display its value using the cout extractor. You can even assign it to another variable. Here is an example:
 

#include <iostream>
using namespace std;

int main()
{
  int Value1 = 250;
  int Value2 = 32;
  int Value3 = !Value1;

  // Display the value of a variable
  cout << "Value1  = " << Value1 << "\n";
  // Logical Not a variable and display its value
  cout << "!Value2 = " << !Value2 << "\n";
  // Display the value of a variable that was logically "notted"
  cout << "Value3  = " << Value3 << "\n";

  return 0;
}

When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was true, which is 1, it would be changed to false, which is 0. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it. This is illustrated in the following example:
 

#include <iostream>
using namespace std;

int main()
{
  int Value1 = 482;
  int Value2 = !Value1;

  cout << " Value1 = " << Value1 << "\n";
  cout << " Value2 = " << Value2 << "\n";
  cout << "!Value2 = " << !Value2 << "\n\n";

  return 0;
}

The Inequality Operator !=

As opposed to Equality, C++ provides another operator used to compare two values for inequality. This operation uses a combination of equality and logical not operators. It combines the logical not ! and a simplified == to produce !=. Its syntax is:

Value1 != Value2

The != is a binary operator (like all logical operator except the logical not, which is a unary operator) that is used to compare two values. The values can come from two variables as in Variable1 != Variable2. Upon comparing the values, if both variables hold different values, the comparison produces a true or positive value. Otherwise, the comparison renders false or a null value.
 

Flowchart: Not Equal

Here is an example:

#include <iostream>
using namespace std;

int main()
{
  int Value1 = 212;
  int Value2 = -46;
  int Value3 = (Value1 != Value2);

  cout << "Value1 = " << Value1 << "\n";
  cout << "Value2 = " << Value2 << "\n";
  cout << "Value3 = " << Value3 << "\n\n";

  return 0;
}

The inequality is obviously the opposite of the equality.

The Comparison for a Lower Value <

To find out whether one value is lower than another, use the < operator. Its syntax is:

Value1 < Value2

The value held by Value1 is compared to that of Value2. As it would be done with other operations, the comparison can be made between two variables, as in Variable1 < Variable2. If the value held by Variable1 is lower than that of Variable2, the comparison produces a true or positive result.
 

Flowchart: Less Than

Here is an example:

#include <iostream>
using namespace std;

int main()
{
  int Value1 = 15;
  int Value2 = (Value1 < 24);

  cout << "Value 1 = " << Value1 << "\n";
  cout << "Value 2 = " << Value2 << "\n\n";

  return 0;
}
 

Combining Equality and Lower Value <=

The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is:

Value1 <= Value2

The <= operation performs a comparison as any of the last two. If both Value1 and Value2 hold the same value, the result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true.
 

Flowchart

Here is an example:

#include <iostream>
using namespace std;

int main()
{
  int Value1 = 15;
  int Value2 = (Value1 <= 24);

  cout << "Value 1 = " << Value1 << "\n";
  cout << "Value 2 = " << Value2 << "\n\n";

  return 0;
}
 

The Comparison for a Greater Value >

When two values of the same type are distinct, one of them is usually higher than the other. C++ provides a logical operator that allows you to find out if one of two values is greater than the other. The operator used for this operation uses the > symbol. Its syntax is:

Value1 > Value2

Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value . Otherwise, the comparison renders false or null.

Flowchart
 

The Greater Than or Equal Operator >=

The greater than and the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is:

Value1 >= Value2

A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result.

Flowchart: Greater Than Or Equal To

Here is a summary table of the logical operators we have studied:

Operator Meaning Example Opposite
== Equality to a == b !=
!= Not equal to 12 != 7 ==
< Less than 25 < 84 >=
<= Less than or equal to Cab <= Tab >
> Greater than 248 > 55 <=
>= Greater than or equal to Val1 >= Val2 <
 

Accessories for Logical Conditions

 

Boolean Variables

The Boolean data type is used to declare a variable whose value would be set as true (1) or false (0). To declare such a value, you use the bool keyword. The variable can then be initialized with a starting value. The Boolean constant is used to check that the state of a variable (or a function) is true or false. You can declare such a variable as:

bool GotThePassingGrade = true;

Later in the program, for a student who got a failing grade, you can assign the other value, like this

GotThePassingGrade = false;

Here is an example:

#include <iostream>
using namespace std;

int main()
{
	bool MachineIsWorking = true;

	cout << "Since this machine is working, its value is "
	        << MachineIsWorking << endl;

	MachineIsWorking = false;	

	cout << "The machine has stopped operating. "
	        << "Now its value is " << MachineIsWorking << endl;

	return 0;
}

Enumerations

An enumeration provides a technique of setting a list of integers where each item of the list is ranked and has a specific name. For example, instead of numbers that represent players of a football (soccer) game such as 1, 2, 3, 4, 5, you can use names instead. This would produce GoalKeeper, RightDefender, LeftDefender, Stopper, Libero. The syntax of creating an enumeration is

enum Series_Name {Item1, Item2, Item_n};

In our example, the list of players by their name or position would be

enum Players { GoalKeeper, RightDefender, LeftDefender, Stopper, Libero };

Each name in this list represents a constant number. Since the enumeration list is created in the beginning of the program, or at least before using any of the values in the list, each item in the list is assigned a constant number. The items are counted starting at 0, then 1, etc. By default, the first item in the list is assigned the number 0, the second is 1, etc. Just like in a game, you do not have to follow a strict set of numbers. Just like a goalkeeper could have number 2 and a midfielder number 22, you can assign the numbers you want to each item, or you can ask the list to start at a specific number.

In our list above, the goalkeeper would have No. 0. To make the list start at a specific number, assign the starting value to the first item in the list. Here is an example:

enum Players { GoalKeeper = 12, RightDefender, LeftDefender, Stopper, Libero };

This time, the goalkeeper would be No. 12, the RightDefender would be No. 13, etc.

You still can assign any value of your choice to any item in the list, or you can set different ranges of values to various items. You can create a list like this:

enum Days { Mon, Tue, Wed, Thu, Fri, Sat, Sun = 0 };

Since Sun is No. 0, Sat would be No. –1, Fri would be –2 and so on. On the other hand, you can set values to your liking. Here is an example:

enum Colors { Black = 2, Green = 4, Red = 3, Blue = 5, Gray, White = 0 };

In this case, the Gray color would be 6 because it follows Blue = 5.

Once the list has been created, the name you give to the list, such as Players, becomes an identifier of its own, and its can be used to declare a variable. Therefore, a variable of the enumerated type would be declared as:

Series_Name Variable;

You can declare more than one variable of such a type. An example of the type of our list of players would be:

Players Defense, Midfield, Attack;

Players HandBall, BasketBall, VolleyBall;

Instead of declaring variables after the list has been created, you can declare the variables of that type on the right side of the list but before the closing semi-colon. Here is an example of a color enumeration and variables declared of that type:

enum Flags {Yellow, Red, Blue, Black, Green, White} Title, Heading1, BottomLine;
#include <iostream>
using namespace std;

main()
{
	enum PizzaSize {psSmall, psMedium, psLarge, psJumbo};	

	cout << "The small pizza has a value of " << psSmall << endl;
	cout << "The medium pizza has a value of " << psMedium << endl;
	cout << "The large pizza has a value of " << psLarge << endl;
	cout << "The jumbo pizza has a value of " << psJumbo << endl;
}

To assign your own values to the list, you could change the enumeration as follows:

enum PizzaSize {psSmall = 4, psMedium = 10, psLarge = 16, psJumbo = 24};

To get the starting as you want, change the enumeration as follows:

#include <iostream>
using namespace std;

main()
{
	enum PizzaSize {psSmall = 4, psMedium, psLarge, psJumbo};	

	cout << "The small pizza has a value of " << psSmall << endl;
	cout << "The medium pizza has a value of " << psMedium << endl;
	cout << "The large pizza has a value of " << psLarge << endl;
	cout << "The jumbo pizza has a value of " << psJumbo << endl;
}

This would produce:

The small pizza has a value of 4
The medium pizza has a value of 5
The large pizza has a value of 6
The jumbo pizza has a value of 7

Press any key to continue...

To assign values at random, you could change the list of pizzas as follows:

enum PizzaSize {psSmall = 2, psMedium, psLarge = 14, psJumbo = -5};

This would produce:

The small pizza has a value of 2
The medium pizza has a value of 3
The large pizza has a value of 14
The jumbo pizza has a value of -5

Press any key to continue...
 

Previous Copyright © 2002-2009FunctionX, Inc. Next