Home > Articles

This chapter is from the book

Making Comparisons with Relational Operators

Questions are a part of life. In addition to asking questions, it is often important to compare things. In programming, you compare values and then execute code based on the answer. The relational operators are used to compare two values. The relational operators are listed in Table 3.2.

Table 3.2 Relational Operators




Greater than


Less than


Equal to


Not equal to


Greater than or equal to


Less than or equal to

When making comparisons with relational operators, you get one of two results: true or false. Consider the following comparisons made with the relational operators:

5 < 10

5 is less than 10, so this is true.

5 > 10

5 is not greater than 10, so this is false.

5 == 10

5 does not equal 10, so this is false.

5 != 10

5 does not equal 10, so this is true.

As you can see, each of these results is either true or false. Knowing that you can check the relationship of values should be great for programming. The question is, how do you use these relations?

Using the if Statement

The value of relational operators is that they can be used to make decisions to change the flow of the execution of your program. The if keyword can be used with the relational operators to change the program flow.

The if keyword is used to compare two values. The standard format of the if command is as follows:

if( val1 [operator] val2)

operator is one of the relational operators; val1 and val2 are variables, constants, or literals; and statement(s) is a single statement or a block containing multiple statements. Remember that a block is one or more statements between brackets.

If the comparison of val1 to val2 is true, the statements are executed. If the comparison of val1 to val2 is false, the statements are skipped. Figure 3.1 illustrates how the if command works.

Figure 3.1Figure 3.1 The if command.

Applying this to an example helps make this clear. Listing 3.4 presents simple usage of the if command.

Listing 3.4 iftest.cs—Using the if Command

 1: // iftest.cs- The if statement
 2: //----------------------------------------------------
 4: class iftest
 5: {                       
 6:   public static void Main()
 7:   {
 8:    int Val1 = 1;
 9:    int Val2 = 0;
11:    System.Console.WriteLine("Getting ready to do the if...");
13:    if (Val1 == Val2)
14:    {
15:      System.Console.WriteLine("If condition was true");
16:    }
17:    System.Console.WriteLine("Done with the if statement");
18:   }
19: }
Getting ready to do the if...
Done with the if statement

This listing uses the if statement in Line 13 to compare two values to see whether they are equal. If they are, it prints Line 15. If not, it skips Line 15. Because the values assigned to Val1 and Val2 in Lines 8–9 are not equal, the if condition fails and Line 15 is not printed.

Change Line 13 to this:

if (Val1 != Val2)

Rerun the listing. This time, because Val1 does not equal Val2, the if condition evaluates to true. The following is the output:

Getting ready to do the if...
If condition was true
Done with the if statement


There is no semicolon at the end of the first line of the if command. For example, the following is incorrect:

if( val != val );
  // Statements to do when the if evaluates to true (which will    // never happen)

val should always equal val, so val != val will be false and the line // Statements to do when the if evaluates to true... should never execute. Because there is a semicolon at the end of the first line, the if statement is ended. This means that the next statement after the if statement is executed—the line //Statements to do when the if evaluates to true.... This line always executes, regardless of whether the if evaluates to true or, as in this case, to false. Don't make the mistake of including a semicolon at the end of the first line of an if statement.

Conditional Logical Operators

The world is rarely a simple place. In many cases, you will want to do more than one comparison to determine whether a block of code should be executed. For example, you might want to execute some code if a person is a female and at least 21 years old. To do this, you execute an if statement within another if statement. The following pseudocode illustrates this:

if( sex == female )
  if( age >= 21 )
    // The person is a female that is 21 years old or older.

There is an easier way to accomplish this—by using a conditional logical operator.

The conditional logical operators enable you to do multiple comparisons with relational operators. The two conditional logical operators that you will use are the AND operator (&&) and the OR operator (||).

The Conditional AND Operator

Sometimes you want to verify that a number of conditions are all met. The previous example was one such case. The logical AND operator (&&) enables you to verify that all conditions are met. You can rewrite the previous example as follows:

If( sex == female && age >= 21 )
  // This person is a female that is 21 years old or older.

You can actually place more than two relationships within a single if statement. Regardless of the number of comparisons, the comparisons on each side of the AND (&&) must be true. For example:

if( x < 5 && y < 10 && z > 10)
  // statements

The statements line is reached only if all three conditions are met. If any of the three conditions in the if statements is false, the statements are skipped.

The Conditional OR Operator

Also sometimes, you do not want all the conditions to be true: Instead, you need only one of a number of conditions to be true. For example, you want might want to execute some code if the day of week is Saturday or Sunday. In these cases, you use the logical OR operator (||). The following illustrates this with pseudocode:

if( day equals sunday OR day equals saturday )
   // do statements

In this example, the statements are executed if the day equals either sunday or saturday. Only one of these conditions needs to be true for the statements to be executed. Listing 3.5 presents both the logical AND and OR in action.

Listing 3.5 and.cs—Using the Logical AND and OR

 1: // and.cs- Using the conditional AND and OR
 2: //----------------------------------------------------
 4: class andclass
 5: {                       
 6:   public static void Main()
 7:   {
 8:    int day = 1;
 9:    char sex = 'f';
11:    System.Console.WriteLine("Starting tests... (day:{0}, sex:{1})",
12:                 day, sex );
14:    if ( day >= 1 && day <=7 )   //day from 1 to 7? 
15:    {
16:      System.Console.WriteLine("Day is from 1 to 7");
17:    }
18:    if (sex == 'm' || sex == 'f' ) // Male or female?
19:    {
20:      System.Console.WriteLine("Sex is male or female.");
21:    }
23:    System.Console.WriteLine("Done with the checks.");
24:   }
25: }
Starting tests... (day:1, sex:f)
Day is from 1 to 7
Sex is male or female.
Done with the checks.

This listing illustrates both the && and || operators. In Line 14, you can see the AND operator (&&) in action. For this if statement to evaluate to true, the day must be greater than or equal to 1 as well as less than or equal to 7. If the day is 1, 2, 3, 4, 5, 6, or 7, the if condition evaluates to true and Line 16 prints. Any other number results in the if statement evaluating to false, and thus Line 16 will be skipped.

Line 18 shows the OR (||) operator in action. Here, if the value in sex is equal to the character 'm' or the character 'f', line 20 is printed; otherwise, Line 20 is skipped.


Be careful with the if condition in Line 18. This checks for the characters 'm' and 'f'. Notice these are lowercase values, which are not the same as the uppercase values. If you set sex equal to 'F' or 'M' in Line 9, the if statement in line 18 would still fail.

Change the values in Lines 8–9, and rerun the listing. You'll see that you get different output results based on the values you select. For example, change Lines 8–9 to the following:

 8:    int day = 9;
 9:    char sex = 'x';

Here are the results of rerunning the program:

Starting tests... (day:9, sex:x)
Done with the checks.

Other times you will want to use the AND (&&) and OR (||) commands together. For example, you might want to execute code if a person is 21 and is either a male or a female. This can be accomplished by using the AND and OR statements together. You must be careful when doing this, though. An AND operator expects the values on both sides of it to be true. An OR statement expects one of the values to be true. For the previous example, you might be tempted to enter the following (note that this is pseudocode):

if( age >= 21 AND gender == male OR gender == FEMALE)
  // statement

This will not accomplish what you want. If the person is 21 or older and is a female, the statement will not execute. The AND portion will result in being false. To overcome this problem, you can force how the statements are evaluated using the parenthesis punctuator. To accomplish the desired results, you would change the previous example to this:

if( age >= 21 AND (gender == male OR gender == female))
  // statement

The execution always starts with the innermost parenthesis. In this case, the statement (gender == male OR gender == female) is evaluated first. Because this uses OR, this portion of the statement will evaluate to true if either side is true. If this is true, the AND will compare the age value to see whether the age is greater than or equal to 21. If this proves to be true as well, the statement will execute.


Use parentheses to make sure that you get code to execute in the order you want.

Do use parentheses to make complex math and relational operations easier to understand.

Don't confuse the assignment operator (=) with the relational equals operator (==).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020